
Node.js Event Loop and Async Behavior
1. What is the order of phases in the Node.js Event Loop?
Phases in order:
- Timers Phase β Executes
setTimeout and setInterval.
- Pending Callbacks Phase β Executes I/O callbacks deferred to the next loop.
- Idle, Prepare Phase β Used internally.
- Poll Phase β Retrieves new I/O events, executes I/O callbacks.
- Check Phase β Executes
setImmediate.
- Close Callbacks Phase β Executes close events like
socket.on('close').
2. Does Poll phase come before Timeout phase?
Yes and No β It depends:
- In normal flow, Timers phase comes before Poll.
- But if youβre inside an I/O callback (like
fs.readFile()), then Poll phase (I/O callback) finishes first, followed by Check (setImmediate) and then Timers (setTimeout).