One of the most common points of confusion in Node.js is knowing when to use setTimeout(), setInterval(), setImmediate(), and process.nextTick(). Each executes at a different priority level within the Libuv Event Loop.
| Function | Loop Execution Phase | Execution Timing | Common Use Case |
|---|---|---|---|
process.nextTick() |
Microtask Queue (Drained between phases) | Immediate (Before next loop phase) | Clean error handling before I/O, emitting events after construction. |
Promise.then() |
Microtask Queue (After nextTick) | Immediate (Before next loop phase) | Standard asynchronous Promise resolutions. |
setTimeout(fn, ms) |
Timers Phase | After minimum ms delay |
Delayed execution, timeouts, polling intervals. |
setImmediate(fn) |
Check Phase | Immediately after Poll phase | Executing code after I/O finishes without waiting for timers. |
setImmediate vs setTimeout Inside I/O CallbacksWhen executed in the root script, the execution order between setTimeout(fn, 0) and setImmediate() can vary based on OS thread scheduling. However, when called inside an I/O callback, setImmediate is 100% deterministic:
const fs = require('fs');
fs.readFile(__filename, () => {
// We are currently in the Poll Phase!
setTimeout(() => {
console.log('2. setTimeout (Timers Phase)');
}, 0);
setImmediate(() => {
console.log('1. setImmediate (Check Phase)');
});
});
Output:
1. setImmediate (Check Phase)
2. setTimeout (Timers Phase)
Why? The I/O callback finished in the Poll Phase. The very next phase in the Libuv cycle is the Check Phase, where setImmediate executes. The Timers phase is not reached until the loop cycles all the way back around!
timer.unref() for Non-Blocking Background Tasks// Keep alive monitoring ping
const pingTimer = setInterval(() => {
console.log('[Ping] Server telemetry running...');
}, 5000);
// Allow the process to exit cleanly when main server closes
pingTimer.unref();
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
See where Timers and Check phases reside.
Understand asynchronous callback execution.
Diagnose event loop lag caused by nextTick abuse.