JavaScript executes code on a single main thread, meaning only one synchronous function runs on the Call Stack at a time. To stay responsive during network requests or timers, browsers and Node.js offload waiting work to background APIs and coordinate results through the Event Loop.
flowchart TD
Stack["1. Call Stack (Synchronous code runs first)"] --> Empty{"Call Stack empty?"}
Empty -- "Yes" --> Micro["2. Drain ALL Microtasks (Promise.then, await)"]
Micro --> Task["3. Run ONE Macrotask (setTimeout, click event)"]
Task --> Empty
Knowing queue priority explains execution order every time:
Promise.then, await, queueMicrotask): Drains every ready microtask before moving on.setTimeout, DOM events): Runs one task per Event Loop turn, allowing the browser to repaint frames in between.Predict the console output below before clicking Run: 1 and 4 run synchronously, 3 runs next as a Promise microtask, and 2 runs last from the timer queue!
console.log("1. Sync start");
setTimeout(() => {
console.log("2. Timeout macrotask");
}, 0);
Promise.resolve().then(() => {
console.log("3. Promise microtask");
});
console.log("4. Sync end");
let data; fetch(url).then(r => data = r); console.log(data); logs undefined because the Promise callback runs later.Promise.resolve().then(loop) starves the Macrotask Queue and freezes UI rendering completely.fetch() requests at once?The browser or Node.js runtime handles network I/O on native background threads outside the JS thread, queuing Promise resolutions back onto the Event Loop when responses arrive.
setTimeout(..., 0)?Because Promises enqueue callbacks in the Microtask Queue, which the Event Loop always drains completely before picking up the next task from the setTimeout Macrotask Queue.
queueMicrotask() used for?queueMicrotask(fn) schedules a small callback directly into the microtask queue right after the current synchronous call stack finishes.
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.