The Event Loop (Micro & Macro Tasks) in JavaScript
The event loop processes work in strict priority: the call stack runs to empty, then ALL queued microtasks (promise reactions, queueMicrotask) drain, then ONE macrotask (timers, I/O, rendering) runs — repeating forever. Microtasks starve rendering if they chain endlessly; a resolved promise's .then always runs before any setTimeout, even a zero-delay one.
This ordering explains every async surprise: await yields to microtasks (not macrotasks), Promise.resolve().then(...) beats setTimeout(..., 0) always, and infinite microtask chains freeze pages exactly like blocking loops do.
Stack first, always
Synchronous code runs to completion before any queued work — nothing preempts the running stack.
Microtasks drain fully
Promise reactions queue as microtasks and ALL run (including newly queued ones) before the next macrotask.
One macrotask per turn
Timers, I/O callbacks, and renders each take one loop turn — interleaved fairly, never starving each other.
Order is deterministic
Stack → microtasks → one macrotask → repeat — every async ordering puzzle resolves through this cycle.
console.log("a");setTimeout(() => console.log("b"), 0);Promise.resolve().then(() => console.log("c"));console.log("d");Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.