Anthony's Blog Site

Node.js Event Loop

May 19, 2025

Node.js Event Loop

Photo Credit: Media


🧠 Node.js Event Loop: Microtasks vs Macrotasks

πŸ“¦ Example

Let’s take a look at this short Node.js script:

console.log("1");

setTimeout(() => console.log("macrotask"), 0);

Promise.resolve().then(() => console.log("microtask"));

console.log("2");

which outputs:

1
2
microtask
macrotask

πŸ” Sequence

This example demonstrates how Node.js handles asynchronous code within a synchronous workflow using the event loop, specifically:

  • The Call Stack executes synchronous code line by line.
  • The Microtask Queue (e.g. Promises, await) runs after the stack is clear but before any macrotasks.
  • The Macrotask Queue (e.g. setTimeout, I/O) runs after all microtasks are complete.

βš™οΈ Step-by-Step Breakdown:

  1. console.log("1") β†’ runs immediately.
  2. setTimeout(..., 0) β†’ schedules a macrotask.
  3. Promise.resolve().then(...) β†’ queues a microtask.
  4. console.log("2") β†’ runs next (still in call stack).
  5. Microtask (console.log("microtask")) runs.
  6. Macrotask (console.log("macrotask")) finally runs.

βœ… Key Takeaways

  • Node.js is single-threaded but asynchronous.
  • Microtasks always run before macrotasks once the call stack is empty.