Event Loop Phases in Node.js
1. Definition
The Event Loop in Node.js works in multiple phases. Each phase has a specific purpose and a queue of callbacks to execute. The loop goes through these phases continuously to process asynchronous operations.
2. Phases Overview
- Timers
- I/O Callbacks
- Idle / Prepare
- Poll
- Check
- Close Callbacks
3. Timers Phase
Executes callbacks scheduled by setTimeout() and setInterval(). These callbacks run after the specified delay (not exactly at that time).
4. I/O Callbacks Phase
Executes callbacks for some system operations like TCP errors or file system operations that were deferred from previous cycles.
5. Idle / Prepare Phase
Internal phase used by Node.js. It is not directly accessible by developers.
6. Poll Phase (Most Important)
- Fetches new I/O events
- Executes I/O callbacks
- Waits if no tasks are available
- Core phase where most work happens
7. Check Phase
Executes callbacks scheduled by setImmediate().
8. Close Callbacks Phase
Executes close events like socket.on('close').
9. Example
setTimeout(() => console.log("Timer"), 0);
setImmediate(() => console.log("Immediate"));
console.log("Start");👉 Output may vary depending on the phase execution order.
10. Execution Order (Simplified)
Timers → I/O → Idle → Poll → Check → Close
11. Why This is Important
- Helps understand async behavior
- Important for debugging
- Frequently asked in interviews
Interview Points
- Event loop has multiple phases
- Poll phase is most important
- setTimeout runs in Timers phase
- setImmediate runs in Check phase