Sub topic 14
process.nextTick and setImmediate
This chapter assumes you already know the Node.js event loop phases (timers, poll, check, and close callbacks) from the previous chapter, and that you know how promise reactions run as microtasks. Node.js adds two scheduling functions that browsers lack, process.nextTick and setImmediate. Their names suggest the opposite of what they do. Here you will see exactly where each callback runs, how they interact with promises, and when to use each one.
The Naming Problem
process.nextTick(fn) does not wait for the next turn of the loop. It runs fn as soon as the current JavaScript operation finishes, before the loop moves on to anything else. setImmediate(fn) does not run immediately. It runs fn in the check phase, which comes after the poll phase of the current or next loop iteration.
The Node.js documentation admits the names are backwards. They were chosen early and cannot be changed without breaking existing code. A useful way to remember them:
nextTickmeans "before anything else happens."setImmediatemeans "on the next pass through the check phase."
| Feature | `process.nextTick` | `setImmediate` |
|---|---|---|
| Queue | nextTick queue (Node.js-specific) | Check phase queue (libuv) |
| Runs | After the current operation, before promise microtasks (in CommonJS) | In the check phase, after poll |
| Can starve I/O | Yes, if it schedules itself recursively | No, new callbacks wait for the next iteration |
| Browser equivalent | Closest is `queueMicrotask` | None standard; `setTimeout(fn, 0)` or `MessageChannel` |
| Typical use | Finish setup before callers continue, emit events after a constructor returns | Yield to I/O, break up long work |
The nextTick Queue and the Microtask Queue
Node.js keeps two queues that both drain between operations: its own nextTick queue and V8's promise microtask queue. An "operation" here means one callback from a loop phase, or the main script itself. When that operation finishes and the call stack is empty, Node.js does the following:
- It drains the nextTick queue completely, including any ticks added while draining.
- It drains the promise microtask queue completely.
- If step 2 added new nextTick callbacks, it goes back to step 1.
Only when both queues are empty does the event loop continue.
Here is the basic case:
// Run as a CommonJS script with Node.js
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// Output: sync, nextTick, promiseThe promise reaction was scheduled first, but the nextTick queue wins because Node.js drains it first.
Interleaving Between the Two Queues
The rule "drain each queue completely" has a consequence that catches people out. A nextTick scheduled from inside a promise callback has to wait until every promise reaction already queued has run:
// Run as a CommonJS script with Node.js
Promise.resolve().then(() => {
console.log('promise 1');
process.nextTick(() => console.log('nextTick inside promise'));
});
Promise.resolve().then(() => console.log('promise 2'));
process.nextTick(() => console.log('nextTick 1'));
console.log('sync');
// Output:
// sync
// nextTick 1
// promise 1
// promise 2
// nextTick inside promiseWhen promise 1 schedules a tick, V8 is in the middle of draining the microtask queue and keeps going until that queue is empty. Only then does Node.js check the nextTick queue again.
setImmediate and the Check Phase
setImmediate callbacks go into the check phase queue, which libuv runs right after the poll phase. Its guarantee is relative to I/O. Inside an I/O callback, a setImmediate callback always runs before a zero-delay timer, because the loop reaches the check phase before it comes back around to timers:
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// Output: immediate, timeoutThe Main-Module Race
Outside an I/O callback, that guarantee goes away:
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// Output varies between runs: sometimes timeout first, sometimes immediate firstNode.js turns a delay of 0 into 1 ms. When the loop starts, it enters the timers phase first. If at least 1 ms has passed since the timer was created, the timer runs first. If not, the timers phase finds nothing ready, and the loop moves through poll to check, so the immediate runs first. How fast the process starts and how busy the machine is decide which one wins. Never rely on this order.
Recursion Does Not Starve the Loop
The check phase only runs callbacks that were already queued when the phase started. A setImmediate scheduled from inside a setImmediate callback waits for the next iteration, so timers and I/O get their turn in between. A recursive process.nextTick does not wait. The nextTick queue drains until it is empty, so a callback that keeps adding ticks keeps the loop from ever moving on.
let ticks = 0;
const start = Date.now();
setTimeout(() => {
console.log(`timer ran after ${ticks} ticks, ${Date.now() - start} ms`);
}, 0);
function spin() {
ticks++;
if (ticks < 1_000_000) process.nextTick(spin);
}
spin();
// The timer waits for all ~1,000,000 ticks to finish.
// Replace process.nextTick with setImmediate and the timer
// runs after only a handful of iterations.Without the counter limit, this would hang the process with no error message. Incoming requests, file reads, and timers would never be handled.
Since Node.js 11, Node.js also drains both the nextTick queue and the microtask queue after each individual setTimeout and setImmediate callback, not only once per phase. This matches browser behavior. If two immediates are queued and the first one resolves a promise, the promise reaction runs before the second immediate.
When to Use Each
Use nextTick to Let the Caller Finish First
The classic use of process.nextTick is emitting an event from a constructor. If the constructor emits right away, no listener has been attached yet. Deferring the emit with a tick lets the caller's synchronous code attach listeners first, while still emitting before any I/O happens:
const EventEmitter = require('events');
class Connection extends EventEmitter {
constructor() {
super();
// Emitting synchronously here would fire before anyone listens.
process.nextTick(() => this.emit('ready'));
}
}
const conn = new Connection();
conn.on('ready', () => console.log('ready'));
// Output: readyThe same reasoning applies to APIs that take a callback. If a function sometimes calls its callback synchronously, for example on a validation error, and sometimes asynchronously, callers cannot reason about ordering. Deferring the synchronous path keeps the API consistently asynchronous:
const fs = require('fs');
function readConfig(path, callback) {
if (typeof path !== 'string') {
process.nextTick(callback, new TypeError('path must be a string'));
return;
}
fs.readFile(path, 'utf8', callback);
}
readConfig(42, (err) => console.log('callback:', err.message));
console.log('after call');
// Output: after call, callback: path must be a stringprocess.nextTick passes any extra arguments after the function on to the callback, as shown here.
Use setImmediate to Yield to I/O
When you split CPU-heavy work into chunks on a server, schedule each chunk with setImmediate. Pending I/O callbacks run in the poll phase between chunks, so the server keeps answering requests. setImmediate also avoids the 1 ms minimum delay that setTimeout(fn, 0) adds to every chunk.
function sumInChunks(numbers, done, chunkSize = 10_000) {
let index = 0;
let total = 0;
function nextChunk() {
const end = Math.min(index + chunkSize, numbers.length);
for (; index < end; index++) total += numbers[index];
if (index < numbers.length) setImmediate(nextChunk);
else done(total);
}
nextChunk();
}
sumInChunks(Array.from({ length: 1_000_000 }, (_, i) => i), (total) => {
console.log('total:', total);
});
// Output: total: 499999500000Common Errors
- Using nextTick to "yield." It does not yield. Pending I/O stays blocked until every tick has run.
- Expecting
setTimeout(fn, 0)andsetImmediateto run in a fixed order in the main module. The order is only guaranteed inside I/O callbacks. - Depending on nextTick-versus-promise order. That order changes between CommonJS and ESM, and when ticks are scheduled from inside promise callbacks.
- Porting browser code that assumes
setImmediateexists. Browsers do not provide it in any standard form.
Exercise
In a CommonJS script, what does this print, and in what order? setImmediate(() => console.log('A')); process.nextTick(() => console.log('B')); Promise.resolve().then(() => console.log('C')); console.log('D');
Show answer
D, B, C, A. The synchronous log runs first. When the main script finishes, Node.js drains the nextTick queue (B), then the promise microtask queue (C). The immediate (A) waits for the check phase of the event loop.
Exercise
A server function processes a large array by calling process.nextTick(processNextChunk) after each chunk. Users report that the server stops answering requests while the job runs. Why, and what one-word change fixes it?
Show answer
The nextTick queue drains completely before the event loop continues, so the chunks run back to back and the poll phase never gets a chance to handle incoming connections. Replacing process.nextTick with setImmediate schedules each chunk in the check phase of a later iteration, which lets pending I/O run between chunks.
Exercise
Inside an fs.readFile callback you schedule setTimeout(t, 0), setImmediate(i), and process.nextTick(n). In what order do t, i, and n run?
Show answer
n, i, t. The nextTick runs as soon as the readFile callback returns. The loop is then in the poll phase, so it moves on to the check phase (i) before it comes back around to the timers phase (t).