Course contentsShow
← JavaScript
Lesson 1207 of 2,72327. The Event LoopFree lesson

setTimeout vs setImmediate (Node.js)

Compare setTimeout with Node's setImmediate and when each schedules callbacks in the event loop.

setTimeout vs setImmediate (Node.js)

You'll learn how setTimeout and Node.js's setImmediate differ in when they schedule callbacks within the event loop.

The Core Difference

Both setTimeout and setImmediate schedule callbacks asynchronously, but they place them in different queues with different timing guarantees.

  • setTimeout(callback, 0) schedules the callback in the task queue (sometimes called the timer queue), but with a minimum delay enforced by the environment
  • setImmediate(callback) (Node.js only) schedules the callback in a special check queue that runs after I/O operations in the current event loop phase

When Each Runs

In Node.js, the event loop has multiple phases. setImmediate is designed to run in the "check" phase, which comes after the poll phase (where I/O callbacks run). Meanwhile, setTimeout timers are checked in their own earlier phase.

The practical result: If you schedule both from the main script (not inside an I/O callback), their execution order is non-deterministic — either could run first depending on system performance. However, if you schedule them inside an I/O callback, setImmediate will always run before setTimeout.

Why setImmediate Exists

setImmediate was created specifically for Node.js to defer execution until after the current event loop phase completes, particularly after I/O events. It's more predictable than setTimeout(fn, 0) for breaking up long-running operations or deferring work.

Key Takeaway: In Node.js, setTimeout schedules callbacks in the timer phase with minimum delays, while setImmediate schedules them in the check phase to run after I/O operations — making setImmediate the preferred choice when you want predictable deferral within the event loop cycle.