Sub topic 14
process.nextTick and setImmediate
This chapter assumes you know the Node.js event loop phases (timers, poll, check) and how the promise microtask queue drains. Node.js adds two scheduling functions that browsers lack. Their names are misleading: process.nextTick runs sooner than setImmediate, which does not run "immediately" at all.
Two Different Queues
process.nextTick(fn) puts fn on the nextTick queue. Node.js drains this queue as soon as the current operation finishes, before the promise microtask queue and before the event loop moves on.
setImmediate(fn) puts fn on the check queue. Its callbacks run in the check phase, which comes right after the poll phase on each loop iteration.
| Function | Queue | When it runs |
|---|---|---|
| `process.nextTick` | nextTick queue | After the current operation, before promise microtasks |
| `Promise.then` / `queueMicrotask` | Microtask queue | After the nextTick queue is empty |
| `setImmediate` | Check queue | Check phase of the loop |
| `setTimeout(fn, 0)` | Timer queue | Timers phase, once at least 1 ms has passed |
nextTick Before Promises
// Run as a CommonJS script: node order.js
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('immediate'));
console.log('sync');
// Output: sync, nextTick, promise, immediatesetImmediate Versus setTimeout
In the main module, the order of setTimeout(fn, 0) and setImmediate(fn) is not deterministic. It depends on whether 1 ms has passed by the time the loop reaches the timers phase. Inside an I/O callback the order is fixed. The loop is already in the poll phase, so the check phase comes next and the timers phase only comes on the following iteration:
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// Output: immediate, timeoutChoosing Between Them
A common reason to use process.nextTick is to let callers attach listeners before an event fires:
const EventEmitter = require('events');
class Job extends EventEmitter {
constructor() {
super();
process.nextTick(() => this.emit('ready'));
}
}
const job = new Job();
job.on('ready', () => console.log('job ready'));
// Output: job readyIf emit ran synchronously in the constructor, no listener would exist yet and the event would be lost.
Node.js keeps draining the nextTick queue until it is empty, so a nextTick callback that schedules another nextTick blocks I/O indefinitely. A recursive setImmediate does not have this problem, because each new immediate waits for the next loop iteration. The Node.js documentation recommends setImmediate (or queueMicrotask) for most cases. Save process.nextTick for when code must run before any other asynchronous work.
Exercise
In a CommonJS script, what does this print, and why? setImmediate(() => console.log('A')); process.nextTick(() => console.log('B')); Promise.resolve().then(() => console.log('C')); console.log('D');
Show answer
D, B, C, A. D is synchronous. After the script finishes, Node.js drains the nextTick queue (B) and then the promise microtask queue (C). The setImmediate callback (A) waits for the check phase of the event loop.
Exercise
A function calls process.nextTick(poll) from inside poll itself to keep checking a flag. Incoming HTTP requests stop being handled. Why, and what is the fix?
Show answer
Node.js drains the nextTick queue completely before moving on, and each call adds a new entry, so the loop never reaches the poll phase where I/O is handled. Replace process.nextTick with setImmediate so each check waits for the next loop iteration and I/O gets processed between checks.