Typorithm · hard

setTimeout vs setImmediate

node-timers-immediatenodejsset-immediateset-timeoutphases
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn setTimeout vs setImmediate

0%

Event Loop

setImmediate runs in the check phase (right after poll) while setTimeout(fn, 0) runs in the timers phase. Inside an I/O callback the loop is already in poll, so check is next and setImmediate always fires before setTimeout(0). Outside any I/O the ordering between the two is nondeterministic.

setImmediate schedules its callback for the check phase, which runs immediately after the poll phase, while setTimeout(fn, 0) schedules for the timers phase at the start of the loop.

Inside an I/O callback you are already in the poll phase, so the very next phase is check — that is why setImmediate always fires before setTimeout(0) in that context.

Outside of any I/O cycle the relative order of setTimeout(fn, 0) and setImmediate is nondeterministic, because it depends on how much time the process spent reaching the loop, which can land either before or after the 1ms timer threshold.

01

setImmediate -> check phase; setTimeout(fn, 0) -> timers phase.

02

Inside I/O, setImmediate always beats setTimeout(0).

03

Outside I/O the ordering of the two is nondeterministic.

// outside any I/O, order is NOT guaranteed
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));

// inside an I/O callback, immediate ALWAYS wins
const fs = require('fs');
fs.readFile('file.txt', () => {
  setTimeout(() => console.log('timeout'), 0); // timers phase
  setImmediate(() => console.log('immediate')); // check phase, runs first
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Timer in timers phase

setTimeout(fn, 0) schedules its callback for the timers phase once the (effectively zero) threshold elapses.

setTimeout(() => console.log('timeout'), 0);

2. Immediate in check phase

setImmediate schedules its callback for the check phase, which runs right after the poll phase.

setImmediate(() => console.log('immediate'));

3. Inside an I/O callback

This callback runs in the poll phase, so the next phase is check — making setImmediate fire before the timer.

fs.readFile('file.txt', () => {

4. Immediate wins after I/O

From inside a poll-phase I/O callback, check is the very next phase, so setImmediate always beats setTimeout(0).

setImmediate(() => console.log('immediate')); // check phase, runs first

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

setTimeout vs setImmediate: Lesson & Practice · Typorithm | ApplyDjinn