Full answer
Node keeps two microtask-style queues that are emptied as soon as the running JavaScript finishes:
- The nextTick queue. Callbacks added with process.nextTick(fn).
- The promise microtask queue. Callbacks from .then, .catch, await, and queueMicrotask.
Node empties the whole nextTick queue first, then the promise queue, and repeats until both are empty. Only then does the event loop go on to the next callback or phase.
setImmediate and setTimeout are real loop callbacks. setImmediate runs in the check phase, directly after poll. setTimeout runs in the timers phase, which comes at the start of the next iteration.
The order of setTimeout(fn, 0) and setImmediate(fn) at the top level of a script is not fixed. It depends on how fast the process starts. Inside an I/O callback the order is fixed: setImmediate always runs first, because the loop is in the poll phase and check comes next.
A practical warning: a nextTick callback that keeps scheduling another nextTick callback starves the loop, because Node never reaches I/O. A recursive setImmediate does not starve it.
const fs = require('node:fs');
// Inside an I/O callback the order is the same every time.
fs.readFile(__filename, () => {
setTimeout(() => console.log('5. setTimeout 0 (next loop iteration)'), 0);
setImmediate(() => console.log('4. setImmediate (check phase)'));
Promise.resolve().then(() => console.log('3. promise then'));
process.nextTick(() => console.log('2. process.nextTick'));
console.log('1. synchronous code in the callback');
});The snippet runs inside an I/O callback on purpose, because that is where the order is guaranteed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. synchronous code in the callback 2. process.nextTick 3. promise then 4. setImmediate (check phase) 5. setTimeout 0 (next loop iteration)
Key points
- nextTick runs before promise callbacks, and both run before the loop continues.
- setImmediate runs in the check phase. setTimeout runs in the timers phase.
- Top-level order of setTimeout 0 and setImmediate is not guaranteed.
- Recursive nextTick can starve I/O. Prefer setImmediate for yielding.
Common mistakes
- Saying setImmediate runs 'immediately', before nextTick.
- Claiming setTimeout 0 always runs before setImmediate, or the opposite, at the top level.
- Using recursive process.nextTick for a long task and freezing the server.
- Mixing up nextTick (Node only) with queueMicrotask (a standard API).
Follow-ups
- Why is the top-level order of setTimeout 0 and setImmediate unpredictable?
- How does await map to these queues?
- How would you split a 1 million item loop so the server stays responsive?
Tips
- Memorise the order: sync, nextTick, promises, immediate, timeout (in an I/O callback).
- Run the snippet yourself and change the order of the calls. The output stays the same.
- Say that nextTick is older and the Node docs now recommend queueMicrotask in most cases.