AceDevHub
Beginner Node.js Interview QuestionsBeginnerComparison

Node.js · Question 7

What is the difference between setImmediate and setTimeout in Node.js?

Direct answer

setImmediate runs in the check phase right after poll; setTimeout(0) runs in the timers phase — order depends on context: outside I/O timers often run first; inside an I/O callback setImmediate usually runs before setTimeout(0).

Why interviewers ask this

This tests whether you understand phase order, not just API names. The answer changes based on whether code runs at top level or inside an I/O callback.

immediate-vs-timeout-top.js
// Top-level — order can vary by runtime load; often timeout first
setTimeout(() => console.log("timeout 0"), 0);
setImmediate(() => console.log("immediate"));
immediate-vs-timeout-io.js
import fs from "node:fs";

fs.readFile(__filename, () => {
  // Inside I/O callback — check phase comes before next timers phase
  setTimeout(() => console.log("timeout inside I/O"), 0);
  setImmediate(() => console.log("immediate inside I/O"));
});
Output
immediate inside I/O
timeout inside I/O
  • setTimeout(0) — minimum delay 1ms in Node (not truly zero); scheduled in timers phase.
  • setImmediate — Node-only; not in browser; preferred to defer after current poll work.
  • Production code — rarely rely on ordering; use explicit Promises or queues for correctness.