I've watched Philip Roberts' presentation on the event loop ( https://www.youtube.com/watch?v=8aGhZQkoFbQ&ab_channel=JSConf ) and I couldn't understand everything.
He says that WebAPIs don't get executed directly on the call stack, they get pushed inside this specific section for WebAPIs and then, when their timer is done ( if they have one ), they get pushed on the task queue. ( The talk about the event loop starts at 12:50 )
On https://developer.mozilla.org/en-US/docs/Web/API, I saw that console
is also a WebAPI.
Does console.log()
also get pushed on the task queue, or do only WebAPIs that have a certain timer, just like setTimeout
or wait for a certain event ( like a click event listener on a button in DOM ) get pushed on the task queue ?
This is what I've tried so far to answer that question:
At minute 13:45 he says this:
The event loop job is to look at the stack and look at the task queue. If the stack is empty, it takes the first thing on the queue and pushed it on to the stack.
However, if I run this code:
console.log("log 1");
while(true){}
console.log("log 2");
I will get log 1
in the console, and then the entire tab will be blocked because of the while(true)
statement. Does that mean that console.log()
is directly executed and it's not pushed on the task queue ? If it would be pushed on the task queue, then it would wait for the call stack to be empty, however, the call stack can't be empty because I have the while(true)
statement in there that will run forever. The console.log("log 1")
is still executed, even if console
is a WebAPI. Does that mean that console.log()
is not pushed on the task queue and only the WebAPIs that have a timer, like setTimeout
, or wait for an event to trigger like addEventListener
from the DOM
WebAPI, get pushed on the task queue ?
Only asynchronous WebAPIs, like DOM Events, fetch, setTimeout, setInterval, etc. are pushed on the callback queue. Synchronous WebAPIs like console for example, are directly executed, without being enqueued on the callback queue.