setImmediate Defers Past I/O Callbacks

Register setImmediate from inside an I/O callback so the check phase runs right after poll — before the timers phase of the next loop iteration.

JavascriptCli Tooling

Code

javascriptsnippet
33 lines
import fs from 'node:fs';

// Write a file, then read it back asynchronously so the poll phase
// has a real I/O completion to process.
fs.writeFileSync('report.txt', 'ready');

fs.readFile('report.txt', 'utf8', (err, data) => {
  console.log('1. poll: I/O callback got', JSON.stringify(data));

  // Registered INSIDE the poll callback: setImmediate queues the check
  // phase, which runs right after poll finishes — before the timers
  // phase of the next loop iteration.
  setImmediate(() => {
    console.log('3. check: setImmediate');
  });
  setTimeout(() => {
    console.log('4. timers: setTimeout 0');
  });

  // Microtasks still cut in before any other phase callback.
  Promise.resolve().then(() => {
    console.log('2. microtask: promise');
  });
});

process.on('exit', () => fs.rmSync('report.txt', { force: true }));

// Observed order (node v24, 13 consecutive runs): poll I/O callback first,
// the microtask drains as soon as that callback returns, then the check
// phase runs setImmediate, and setTimeout 0 waits for the next iteration's
// timers phase. Registering these at top level instead gives a different,
// also-reproducible order — timers before check — because no poll callback
// is pending when the loop starts.

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1. poll: I/O callback got "ready"
2. microtask: promise
3. check: setImmediate
4. timers: setTimeout 0

How the snippet works

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Points of care

  • The dependency surface is just node:fs, and that one is built into Node.js.

Applying it

The run emits 4 labeled sections — 1. poll: I/O callback got, 3. check: setImmediate, 4. timers: setTimeout 0, 2. microtask: promise — one per step.

Statements that matter

Promise.resolve().then(() => {
  console.log('2. microtask: promise');
});
process.on('exit', () => fs.rmSync('report.txt', { force: true }));
setImmediate(() => {
  console.log('3. check: setImmediate');
});

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:fs` ships with Node.js itself.