setImmediate
- Node.js course
- Expert
- Lesson 17/47
- 5 min
Learn setImmediate and the check phase.
setImmediate
setImmediate runs a callback in the check phase. It is similar to setTimeout(fn, 0) but they run in different phases. In an I/O cycle setImmediate always runs before setTimeout.
An executionOrder() function models this order: ['timer', 'io', 'immediate'].join(' -> ') returns 'timer -> io -> immediate'. This shows the phase order in one turn with a fixed string: first timer (setTimeout), then I/O (poll), then immediate (setImmediate). The output is timer -> io -> immediate. In real Node.js this order is consistent in an I/O cycle; setImmediate runs in the check phase right after I/O. The model is deterministic.
The check phase
setImmediate calls run in the check phase. This phase comes right after poll. When an I/O operation finishes the event loop moves from poll to check; so the setImmediate callback runs right after the I/O callback.
Example: executionOrder() returns 'timer -> io -> immediate'. In this string io represents the poll phase and immediate the check phase. The order is: timer (setTimeout) then I/O (poll) then immediate (setImmediate). It may seem odd that setImmediate appears after setTimeout(fn, 0); but in an I/O cycle setImmediate always runs first because the check phase comes before the next timers phase. The output is deterministic.
Practice Write the execution order
Write function executionOrder(). Return ['timer', 'io', 'immediate'].join(' -> '). Print console.log(executionOrder()).
Starter code
// Write an executionOrder function
// Join the ['timer', 'io', 'immediate'] array
// Separate with ' -> ' and print
// write hereSample solution
function executionOrder() {
return ['timer', 'io', 'immediate'].join(' -> ');
}
console.log(executionOrder());Expected output
timer -> io -> immediate
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the join call
return ['timer', 'io', 'immediate'].____(' -> ');
return ['timer', 'io', 'immediate'].join(' -> ');
Explanation: join combines the array into a string.
2 Match each concept to its description
| Term | Meaning |
|---|---|
setImmediate |
Runs in the check phase |
check |
Phase after poll |
setTimeout |
Runs in the timers phase |
poll |
Processes I/O events |
3 In which phase does a setImmediate callback run?
- timers
- check Correct answer
- poll
- close
Explanation: setImmediate runs in the check phase.