Event loop phases
- Node.js course
- Expert
- Lesson 13/47
- 5 min
Learn the event loop phases (poll, check, close).
Event loop phases
The Node.js event loop consists of six phases: timers, pending callbacks, idle/prepare, poll (I/O events), check (setImmediate) and close. Each turn the loop visits these phases in order.
An eventLoopPhases() function models this order: it returns ['timers', 'pending', 'idle', 'poll', 'check', 'close']. In the timers phase setTimeout callbacks run. In the poll phase I/O events are processed. In the check phase setImmediate calls run. Knowing the phase order is the key to understanding when a callback runs. The output is timers -> pending -> idle -> poll -> check -> close.
Phase order
The event loop visits phases in a fixed order each turn. It starts with timers and ends with close; then a new turn begins. This order sets the priority of different callback types.
Example: eventLoopPhases() returns ['timers', 'pending', 'idle', 'poll', 'check', 'close']. .join(' -> ') turns it into one string: timers -> pending -> idle -> poll -> check -> close. Knowing this order explains why a setTimeout callback runs before setImmediate (at the same delay): the timers phase comes before the check phase. The phase order is the skeleton of the event loop.
Practice Write the phase order
Write function eventLoopPhases(). Return ['timers', 'pending', 'idle', 'poll', 'check', 'close']. Print console.log(eventLoopPhases().join(' -> ')).
Starter code
// Write an eventLoopPhases function
// Return the six phase names as an array
// Join with ' -> ' and print
// write hereSample solution
function eventLoopPhases() {
return ['timers', 'pending', 'idle', 'poll', 'check', 'close'];
}
console.log(eventLoopPhases().join(' -> '));Expected output
timers -> pending -> idle -> poll -> check -> close
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which phase do setTimeout callbacks run?
- poll
- timers Correct answer
- check
- close
Explanation: setTimeout callbacks run in the timers phase.
2 Write the first phase name
function eventLoopPhases() { return ['____', 'pending', 'idle', 'poll', 'check', 'close']; }
function eventLoopPhases() { return ['timers', 'pending', 'idle', 'poll', 'check', 'close']; }
Explanation: timers is the first phase of the event loop.
3 Match each phase to its role
| Term | Meaning |
|---|---|
timers |
setTimeout callbacks |
poll |
I/O events |
check |
setImmediate |
close |
Close callbacks |