Chapter XV · The Event Loop

How the Event Loop Works

The event loop runs an endless loop checking the call stack and queues, prioritizing microtasks over macrotasks.

01 How It Works

Think of a priority checkout lane where VIP priority queue members are always served before general queue customers.

It empties the call stack first, clears the entire microtask queue, executes one macrotask, updates rendering if needed, and repeats.

example.js
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
  1. 1. Stack runs main script sync code.

  2. 2. Stack becomes empty -> Event loop drains all microtasks.

  3. 3. Event loop picks one macrotask and pushes it to the stack.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
queueMicrotask(() => console.log("Microtask 1"));
setTimeout(() => console.log("Macrotask 1"), 0);

Key Takeaway

The event loop strictly prioritizes microtasks over macrotasks after every stack clearance.

Related Concepts