Chapter XV · The Event Loop
Event Loop
The Event Loop is a continuous monitoring mechanism that coordinates execution between the call stack, task queues, and microtask queues.
01 How It Works
Think of an attentive restaurant manager continuously checking if kitchen chefs are free to take new orders.
The event loop checks if the call stack is empty. If it is, it takes pending tasks from the queues and pushes them onto the stack for execution.
example.js
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
1. Execute all synchronous code on the call stack.
2. Process all microtasks in the microtask queue entirely.
3. Process a single task from the macrotask queue and repeat.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
setTimeout(() => console.log("Macro task"), 0);
Promise.resolve().then(() => console.log("Micro task"));
console.log("Sync code");
// Output order: Sync code -> Micro task -> Macro task
Key Takeaway
The Event Loop enables JavaScript's non-blocking asynchronous concurrency model.