7

Most examples explaining the concurrency model of JavaScript in the browser list three parts: The call stack, the web api's, and the event queue. The normal process which is often described is that Web APIs are not handled by core ECMAScript and are handled by a web API; at this point they move into the event queue to wait until the call stack is empty to be executed. setTimeout is often used as an example to this process.

My questions are:

1.) since console.log is a web API, why does it not enter the event queue behind setTimeout? (does it even enter the event queue at all)?

2.) If it doesn't enter the event queue, what determines what APIs get pulled out of the call stack to go through the event loop process? Is it only those APIs which wait for something and have callbacks?

setTimeout(function(){
  doSomething();
},0);

console.log('Hello World!');
7
  • 2
    because console.log isn't asynchronous. Think of the "event queue" as more of a "callback queue". also, you left out the "event loop" in your process description. It's different from the callback queue. Commented Mar 29, 2018 at 19:39
  • Thank you. That helps confirm what I was thinking. Commented Mar 29, 2018 at 19:44
  • Maybe related? not necessarily dupe, but it explains the event loop. stackoverflow.com/questions/39459236/… Commented Mar 29, 2018 at 19:45
  • 1
    @BenjaminGruenbaum I think I'd differentiate asynchronous and live or something may? The call to console.log absolutely should be described as synchronous, it just reflects a live representation of the object generally. Commented Mar 29, 2018 at 20:53
  • 3
    @loganfsmyth the call executes synchronously but it queues an event that runs asynchronously, the only difference is that you can't listen to when it's done (no callback). The only guarantee is that console.log calls are sequenced - notice that the fact there is no console input (in the browser) except the REPL (which lets you enter a command again after everything has finished printing) greatly simplifies this. Commented Mar 29, 2018 at 21:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.