JavaScript
Master how JavaScript handles asynchronous operations, the Call Stack, Microtasks, and the Macrotask Queue.
The Event Loop in Simple Words
JavaScript is single-threaded, meaning it can only do one single thing at a time. Yet, your browser can download files, set timers, and handle user clicks without freezing. The Event Loop is the secret coordinator that manages what code runs and when.
Imagine a busy bank with a single teller window:
- The Teller (Call Stack): Handles only 1 customer at a time directly until done.
- The Back Office (Web APIs): Where background tasks happen (like counting vault money or waiting for a courier timer).
- The VIP Line (Microtask Queue): High-priority customers (Promises). The teller must clear every single VIP before taking anyone from the main lobby!
- The General Waiting Lobby (Macrotask Queue): Standard ticket holders (
setTimeout,setInterval). Handled one by one only when VIPs are empty. - The Bank Manager (Event Loop): Constantly monitors: "Is the teller free? If yes, send the next VIP customer. If no VIPs, call the next lobby ticket!"
The Execution Order Blueprint
Whenever JavaScript runs a script, it follows this strict priority order:
1. Synchronous Code
Runs immediately on the Call Stack line by line until completely empty.
2. Microtasks (VIP)
Promise.then(), catch(), and queueMicrotask() run right after stack empties.
3. Macrotasks
setTimeout, setInterval, and DOM events run one task per tick.
The Classic Asynchronous Puzzle
console.log("1. Synchronous Start");
setTimeout(() => {
console.log("2. Macrotask (setTimeout 0ms)");
}, 0);
Promise.resolve().then(() => {
console.log("3. Microtask (Promise 1)");
}).then(() => {
console.log("4. Microtask (Promise 2)");
});
console.log("5. Synchronous End");
1. Synchronous Start 5. Synchronous End 3. Microtask (Promise 1) 4. Microtask (Promise 2) 2. Macrotask (setTimeout 0ms)
Microtasks vs Macrotasks Comparison
| Feature | Microtask Queue (VIP) | Macrotask Queue (Lobby) |
|---|---|---|
| Sources | Promise.then(), async/await, queueMicrotask() |
setTimeout(), setInterval(), setImmediate() |
| Drain Rate | All queued microtasks are drained completely in one turn. | Only 1 macrotask is executed before re-checking microtasks. |
| Priority | High Priority | Standard Priority |
Hands-On Practice: Event Loop Queue Schedulers
Write a script that demonstrates all three stages in order: Log "1. Stack" synchronously, schedule "2. Microtask" with Promise.resolve().then(), and schedule "3. Macrotask" with setTimeout.