The Node.js Event Loop Explained
Understanding the event loop is fundamental to writing performant Node.js applications. Let’s break down each phase and see how they work together.
The Six Phases
- Timers — executes
setTimeoutandsetIntervalcallbacks - Pending callbacks — executes I/O callbacks deferred to the next loop iteration
- Idle, prepare — used internally by Node.js
- Poll — retrieves new I/O events
- Check —
setImmediate()callbacks are invoked here - Close callbacks —
socket.on('close', ...), etc.
Common Pitfalls
// This blocks the event loop!
app.get('/heavy', (req, res) => {
const result = heavyComputation(); // synchronous!
res.json(result);
});
// Better: offload to a worker
app.get('/heavy', async (req, res) => {
const result = await runInWorker(heavyComputation);
res.json(result);
});
Key Takeaways
- Never block the event loop with synchronous computation
- Use worker threads for CPU-intensive tasks
- Understand the difference between
setImmediateandprocess.nextTick