6

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!');
Brandon
  • 1,747
  • 2
  • 13
  • 22
  • 1
    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. – Kevin B Mar 29 '18 at 19:39
  • Thank you. That helps confirm what I was thinking. – Brandon Mar 29 '18 at 19:44
  • Maybe related? not necessarily dupe, but it explains the event loop. https://stackoverflow.com/questions/39459236/understanding-event-queue-and-call-stack-in-javascript?rq=1 – Kevin B Mar 29 '18 at 19:45
  • Actually console.log is asynchronous, it's just executed (but doesn't terminate) synchronously. So even if it wasn't completely synchronous you wouldn't know because other things logging would just write their logs later than you do (and also asynchronously). The only thing I know that truly qualifies is `alert`. – Benjamin Gruenbaum Mar 29 '18 at 19:49
  • eh, that's a good point. I think more what i meant was it doesn't enter the callback queue, there's no reason for it to. There's no callback or additional work that the js engine needs to do when it completes and no reason for it to have any impact on the event loop. – Kevin B Mar 29 '18 at 19:54
  • 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. – loganfsmyth Mar 29 '18 at 20:53
  • 2
    @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. – Benjamin Gruenbaum Mar 29 '18 at 21:41

0 Answers0