The JavaScript Event Loop: Call Stack, Microtasks, and Why setTimeout(0) Lies
How the call stack, Web APIs, macrotask queue, and microtask queue actually schedule your code—and why Promise.resolve() always cuts in line ahead of setTimeout(0).
You'll learn the exact order JavaScript runs synchronous code, Promises (microtasks), and setTimeout / events (macrotasks), why setTimeout(fn, 0) never means "run right now", and how starving the microtask queue freezes the browser. Assumes familiarity with Promises and async/await.
1. The puzzle that breaks everyone's intuition
Predict the exact output of these six lines before reading further:
console.log("1: sync");
setTimeout(() => console.log("2: timeout"), 0);
Promise.resolve().then(() => console.log("3: promise"));
console.log("4: sync");If you guessed 1, 2, 3, 4—or even 1, 4, 2, 3 because setTimeout(..., 0) was registered first—you fell for the trap. The actual output is:
1: sync
4: sync
3: promise
2: timeoutPromise cut in line ahead of setTimeout(..., 0), even though setTimeout had a 0ms delay and was written first. To understand why, you need to see the four moving parts of the browser's runtime.
2. The four pieces of the runtime
- The Call Stack: Where synchronous JavaScript runs right now, one function frame at a time. While code is on the call stack, nothing else runs—not
setTimeout, not Promises, not even browser paint. - Web APIs: Browser-managed features outside the JS engine (
fetch,setTimeout, DOM events). When their timer or network trip finishes, they do not interrupt the call stack—they drop a callback into a queue. - The Task Queue (Macrotasks): Holds callbacks from
setTimeout,setInterval,clickevents, andpostMessage. - The Microtask Queue: Holds
.then()/.catch()callbacks,asynccontinuations afterawait, andqueueMicrotask().
3. The Event Loop's strict rule
The Event Loop is an endless while-loop inside the browser with one ironclad priority order:
- Run everything currently on the Call Stack until it is completely empty.
- Drain the entire Microtask Queue—and if a microtask schedules another microtask, run that one too, until the microtask queue is 100% empty.
- (If it's time for a 16.6ms frame) Let the browser Render / Paint pixels.
- Pick one task from the Macrotask Queue, run it on the Call Stack, and repeat from step 1.
Now re-read our six-line puzzle with that rule in mind:
console.log("1: sync")runs immediately on the Call Stack.setTimeout(..., 0)hands a timer to Web APIs, which queues"2: timeout"into the Macrotask Queue.Promise.resolve().then(...)queues"3: promise"into the Microtask Queue.console.log("4: sync")runs on the Call Stack.- Call Stack is now empty -> Event Loop drains the Microtask Queue -> prints
"3: promise". - Microtask Queue is empty -> Event Loop picks the next Macrotask -> prints
"2: timeout".
setTimeout(fn, 0) does not mean "run in 0ms." It means "run no sooner than 0ms, after the current stack and all pending microtasks and earlier tasks finish." (And browsers clamp nested timers to at least 4ms anyway.)
Paste the 6-line snippet into your browser Console and verify it prints 1, 4, 3, 2 every single time.
4. How microtasks can accidentally freeze a page
Notice step 2 above: the Event Loop drains the entire microtask queue before the browser is allowed to paint a single pixel or handle a click.
That means a recursive setTimeout is safe (the browser paints between each task), while a recursive Promise freezes the tab dead:
// SAFE: yields back to the browser between each tick
function safeLoop() {
setTimeout(safeLoop, 0);
}
// FREEZES TAB: microtask queue never empties, Paint never runs
function doomLoop() {
Promise.resolve().then(doomLoop);
}Never run doomLoop() in a tab you care about—it starves rendering completely.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Assuming setTimeout(fn, 0) runs immediately | Runs after current stack and all microtasks | Use queueMicrotask() if it must run before paint, or call directly |
Expecting setTimeout to keep exact wall-clock time | Long sync work delays timers indefinitely | Compare timestamps (performance.now()) instead of counting ticks |
| Infinite microtask recursion | Browser tab freezes, clicks/paint stop | Yield with setTimeout or requestAnimationFrame |
Practice
Predict the output before running:
console.log("start");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve()
.then(() => console.log("p1"))
.then(() => console.log("p2"));
console.log("end");Answer: start, end, p1, p2, timeout. Both chained .then() microtasks drain completely before the macrotask timeout runs.
What you learned
- Synchronous code empties the Call Stack first.
- Microtasks (Promises,
awaitcontinuations,queueMicrotask) drain completely before the browser renders or runs the next Macrotask (setTimeout, DOM events). setTimeout(fn, 0)only means "enqueue for a future macrotask turn", never "run immediately".