Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)
Node.js Event Loop Phases in exact order.
In Simple Words: The Event Loop continuously executes tasks in 6 distinct phases in this exact order:
- Timers: Executes callbacks scheduled by
setTimeout()andsetInterval(). - Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration (e.g., TCP socket errors).
- Idle, Prepare: Used internally by Node.js.
- Poll: Retrieves new I/O events, executes I/O-related callbacks (file read, network sockets). If no timers are pending, blocks and waits for connections.
- Check: Executes callbacks registered by
setImmediate(). - Close Callbacks: Executes close events (e.g.,
socket.on('close', ...)).
javascript
// Execution order demonstration:
setTimeout(() => console.log('1. Timers Phase (setTimeout)'), 0);
setImmediate(() => console.log('3. Check Phase (setImmediate)'));
process.nextTick(() => console.log('0. Microtask Queue (nextTick)'));
console.log('Main synchronous script');