The Event Loop is the foundational architectural component that allows single-threaded JavaScript to handle non-blocking, highly concurrent operations. If you understand the Event Loop, you understand the true runtime behavior of asynchronous JavaScript.
Figure 14: JavaScript Concurrency Model: Call Stack, Web APIs, Microtask Queue (VIP), Macrotask Queue, and Event Loop.
.then, .catch, .finally), queueMicrotask(), and async/await continuations.setTimeout, setInterval, setImmediate, and I/O events.Predict the exact output order of this script:
console.log("1. Synchronous Global Script");
setTimeout(() => {
console.log("2. Inside setTimeout (Macrotask)");
}, 0);
Promise.resolve().then(() => {
console.log("3. Inside Promise 1 (Microtask)");
}).then(() => {
console.log("4. Inside Promise 2 (Microtask)");
});
console.log("5. End of Global Script");
| Output Order | Printed Line | Queue Source & Mechanical Explanation |
|---|---|---|
| 1st | "1. Synchronous Global Script" | Executed immediately in Call Stack. |
| 2nd | "5. End of Global Script" | Synchronous execution completes; Call Stack becomes empty. |
| 3rd | "3. Inside Promise 1 (Microtask)" | Event Loop drains Microtask Queue FIRST before any timer. |
| 4th | "4. Inside Promise 2 (Microtask)" | Chained Promise microtask executed next in Microtask Queue. |
| 5th | "2. Inside setTimeout (Macrotask)" | Microtask Queue is empty! Event Loop picks task from Macrotask Queue. |
The Golden Rule of Event Loop Priority:
Synchronous Code in Call Stack > Microtask Queue (Promises) > Macrotask Queue (Timers)
How do large web applications split code across files using modules? Proceed to: JavaScript ES Modules (ESM: import & export) →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Pausing and resuming microtask functions.
Microtask queue priority over macrotasks.
Browser timer queues in the event loop.
Call stack interactions with event loop.