Event Loop Explained
Why the Event Loop Matters
The event loop is the core mechanism that makes Node.js efficient. Without understanding it, many production bugs appear “random”. With understanding, they become predictable.
The Core Idea
Node runs JavaScript on a single thread. Instead of blocking while waiting for operations (like file reads or network requests), Node registers callbacks and continues executing other tasks. When an operation finishes, its callback is queued and later executed by the event loop.
Single Thread Does Not Mean Single Request
Node can handle many concurrent requests because most of the waiting happens outside JavaScript execution. The event loop keeps cycling, checking queues, and executing ready tasks.
The Event Loop Phases (Simplified)
- Timers (setTimeout, setInterval)
- Pending Callbacks
- Poll (I/O callbacks)
- Check (setImmediate)
- Close Callbacks
Microtasks vs Macrotasks
Promises (and process.nextTick) are microtasks. They run before the event loop continues to the next phase. Timers and I/O callbacks are macrotasks. Misunderstanding this difference can cause starvation or unexpected ordering.
Example: Execution Order
console.log('start');
setTimeout(() => {
console.log('timeout');
}, 0);
Promise.resolve().then(() => {
console.log('promise');
});
console.log('end');
Expected Output
start end promise timeout
Why Promise Runs Before Timeout
Promise callbacks are placed in the microtask queue. The event loop always drains the microtask queue before moving to the next phase.
Blocking the Event Loop
If you execute heavy CPU work (like a large loop or JSON parsing of huge objects), the event loop cannot move forward. That means no other requests can be processed.
Example of Blocking Code
while (true) {
// infinite loop blocks everything
}
Production Rule
- Never block the event loop.
- Offload CPU-heavy tasks to worker threads.
- Use streaming for large payloads.
Event Loop Lag
In production systems, high CPU or synchronous operations increase event loop lag. Monitoring this metric helps detect performance degradation before users complain.
JS Note
The event loop behavior is the same in JavaScript and TypeScript. TypeScript adds type safety, not runtime behavior changes.
What Comes Next
Now that you understand how Node schedules work, we can properly set up a project and run code safely in a controlled environment.