I continue to see explanations of the “Javascript event loop” (ie the JS event loop for launching the browser) that seem unbelievable to me, and I hope someone can provide some authoritative clarification.
My basic oscillation is that the JS event loop is similar to the event loops that we have been working with in user interface interfaces for decades, for example:
// [... some initialization ...] // The Event Loop while (true) { if (! EventQueue.isEmpty()) { event = EventQueue.pop_oldest_item(); event.callback(event [or some other kind of args]); } // [... defer to other non-JS tasks...] }
But I continue to see explanations (see examples below):
Event loop:
Checks if the call stack is empty (Javascript).
Checks if there is a callback queue [AKA EventQueue].
If the call stack is empty and the callback queue is NOT empty, then:
a. Exit the oldest callback queue item.
b. Push this callback function onto the call stack (and no mention of calling this function.)
Continue the cycle.
This clearly vaguely follows my proposed model above, but with two key and alarming differences:
a. Why should the event loop check that the JS call stack is empty? Of course, every time around the loop, the call stack will be in the same state (regardless of whether it is completely “empty” near the point, it does not need a “check”). Any function called last time will return, restoring the stack. Therefore, this part does not make sense.
Q. Why is the event loop "pushing the callback onto the JS stack"? Shouldn't the event loop simply call the function, thereby creating a legitimate stack stack and a way to return from the function, not to mention the actual execution of the function?
Therefore, I would appreciate an explanation that addresses these explanations and why they are actually true, or reinforces my strong suspicion that they are incorrect.
Examples of sources for these explanations of the event loop:
Philip Roberts: What the hell is an event loop? At 14:00 https://youtu.be/8aGhZQkoFbQ?t=839
Typescript High Performance (Book) p. 83.
What is a Javascript event loop? http://altitudelabs.com/blog/what-is-the-javascript-event-loop/
Understanding the performance of Javascript functions - call stack, event loop, tasks and much more https://medium.com/@gaurav.pandvia/understanding-javascript-function-executions-tasks-event-loop-call-stack-more-part- 1-5683dea1f5ec