Stickied: Required Watching
Stickying the Philip Roberts JSConf EU talk as required watching for this thread. It's 26 minutes and will save you hours of confusion.
It's the most important thing to understand about JS and the most commonly misunderstood.
Stickying the Philip Roberts JSConf EU talk as required watching for this thread. It's 26 minutes and will save you hours of confusion.
Philip Roberts' talk 'What the heck is the event loop anyway?' on YouTube and the Loupe visualiser at latentflip.com/loupe are the best resources I have found. Watching the stack, queue, and heap animate in real time makes it concrete.
setTimeout(fn, 0) does not run immediately — it queues a macrotask. The callback runs after the current call stack and all pending microtasks have cleared. It is useful for yielding control back to the browser to repaint, but it is not truly zero-delay.
There are two queues. Microtasks (Promise callbacks, queueMicrotask) drain completely before the next macrotask (setTimeout, setInterval, I/O callbacks) runs. This is why a resolved Promise callback always fires before a setTimeout(fn, 0).