Skip to main content

Demo 32

setImmediate after I/O

Inside an I/O callback, setImmediate usually runs before a zero-delay timer.

fully simulatedcurated scenariodoes not execute real code
Short answer

The key output order is io done -> immediate -> timeout. After I/O, Node's check phase gives setImmediate a predictable advantage over a new timer.

Real-world bug this helps solve

A Node callback, timer, I/O task, stream, or worker-pool job runs later than expected. This appears in servers, CLIs, file watchers, and test suites that schedule follow-up work after I/O.

Common wrong assumption

Expecting setTimeout(..., 0) to always beat setImmediate.

Fix direction

Separate sync work, microtasks, timers, I/O, check callbacks, and worker-pool work in your mental model.

Fixed code pattern
setImmediate(runAfterIO);
// Avoid long nextTick loops that starve other phases.
Visual proof

The console lane proves the visible order: io done -> immediate -> timeout. The active line and queues show why source order changed.

How to verify in a real app

Add timestamps around callbacks and inspect Node diagnostics, logs, or profiler output to confirm the runtime phase that is delaying work.

Share
Loading visual timeline...

Related cases

Continue with nearby confusion while the mental model is fresh.

Recommended next

Was this clear?

This stays local for now. It helps you track where the product still needs sharper cases.

Send detail