JavaScript executes code on a single thread. Asynchronous non-blocking concurrency is enabled by the runtime Event Loop, which orchestrates execution across the Call Stack, Web APIs, Macrotask Queue, and Microtask Queue.
flowchart TD
CallStack["1. Call Stack (Synchronous Code Execution)"]
WebAPIs["Web APIs (Timers, Fetch, DOM Events)"]
MicroQueue["Microtask Queue (Promises, queueMicrotask, MutationObserver)"]
MacroQueue["Macrotask Queue (setTimeout, setInterval, I/O)"]
CallStack -->|Offload Async Tasks| WebAPIs
WebAPIs -->|Promises Resolve| MicroQueue
WebAPIs -->|Timer/IO Ready| MacroQueue
CallStack -->|Stack Clears| EventLoop{"Event Loop Processing"}
EventLoop -->|Priority 1: Drain ALL Microtasks| MicroQueue --> CallStack
EventLoop -->|Priority 2: Process 1 Macrotask| MacroQueue --> CallStack
| Queue Type | Member Tasks | Queue Drain Behavior | Priority |
|---|---|---|---|
| Microtask Queue | Promise.then(), queueMicrotask(), MutationObserver |
Drains ALL microtasks completely before next render/macrotask. | Highest |
| Macrotask Queue | setTimeout, setInterval, setImmediate, I/O |
Processes ONE macrotask per event loop tick. | Lower |
// Demonstrating Event Loop execution order (Sync vs Microtasks vs Macrotasks)
console.log("1. Synchronous Start");
// Macrotask (setTimeout)
setTimeout(() => {
console.log("5. Macrotask (setTimeout 0ms)");
}, 0);
// Microtask (Promise)
Promise.resolve().then(() => {
console.log("3. Microtask 1 (Promise.then)");
}).then(() => {
console.log("4. Microtask 2 (Promise.then chain)");
});
// Microtask (queueMicrotask)
queueMicrotask(() => {
console.log("3b. Microtask (queueMicrotask)");
});
console.log("2. Synchronous End");
// Output Order:
// 1. Synchronous Start
// 2. Synchronous End
// 3. Microtask 1 (Promise.then)
// 3b. Microtask (queueMicrotask)
// 4. Microtask 2 (Promise.then chain)
// 5. Macrotask (setTimeout 0ms)
setTimeout.function loop() { Promise.resolve().then(loop); }) starves the macrotask queue and completely freezes browser UI rendering.for (let i=0; i<1e9; i++)) block the call stack, preventing microtasks and event listeners from executing.Predict the exact console output sequence of a script containing console.log("A"), setTimeout(() => console.log("B"), 0), and Promise.resolve().then(() => console.log("C")).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.