JS Asynchronous
JavaScript Asynchronous Architecture: The Event Loop Explained
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.
Call Stack, Microtasks, and Task Queue Priority
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:
- Synchronous Call Stack: Runs top-to-bottom until empty.
- Microtask Queue (
Promise.then,await,queueMicrotask): Drains every ready microtask before moving on. - Task / Macrotask Queue (
setTimeout, DOM events): Runs one task per Event Loop turn, allowing the browser to repaint frames in between.
Execution Order Example
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");
Common Mistakes to Avoid
- Blocking the main thread with heavy synchronous loops: A synchronous loop taking 2 seconds freezes button clicks, scrolling, and timers because the Call Stack never clears for the Event Loop.
- Expecting async results synchronously on the next line: Writing
let data; fetch(url).then(r => data = r); console.log(data);logsundefinedbecause the Promise callback runs later. - Spawning infinite recursive microtasks: Recursively calling
Promise.resolve().then(loop)starves the Macrotask Queue and freezes UI rendering completely.
Frequently Asked Questions
If JavaScript is single-threaded, how does it handle multiple 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.
Why do Promises run before 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.
What is queueMicrotask() used for?
queueMicrotask(fn) schedules a small callback directly into the microtask queue right after the current synchronous call stack finishes.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.