I've read several posts/SO threads on event loop, and according to MDN's article,
When the stack is empty, a message is taken out of the queue and processed.
As a JS novice, what I'm still confused about is -- when exactly does the call stack become "empty"? For example,
<script>
function f() {
console.log("foo");
setTimeout(g, 0);
console.log("foo again");
}
function g() {
console.log("bar");
}
function b() {
console.log("bye");
}
f();
/*<---- Is the stack empty here? */
b();
</script>
The correct order of execution is foo
- foo again
- bye
- bar
.
But today I started thinking: isn't the stack technically empty right after exiting the f()
call? I mean at that point we're not inside any function, and we haven't started any new execution, so shouldn't the setTimeout
call message (which has been immediately queued) be processed, before moving on to b()
, and giving the order of foo
- foo again
- bar
- bye
?
What if we have a million lines of code or some intensive computation to be executed and the setTimeout(func, 0)
just sits in the queue for however long?
Although the block of code within the <script>
tags isn't wrapped in an explicit function, it can be helpful to think of it as being a global function that the browser tells the javascript runtime to execute. So the call stack isn't empty until the code in the script block is done executing.