Difference between setTimeout and setImmediate

1. Definition

Both setTimeout() and setImmediate() are used to execute asynchronous callbacks in Node.js, but they run in different phases of the Event Loop.

2. setTimeout()

setTimeout() schedules a callback to run after a minimum delay (in milliseconds). It executes in the Timers phase of the Event Loop.

3. setImmediate()

setImmediate() schedules a callback to run immediately after the current I/O operations are completed. It executes in the Check phase.

4. Key Differences

  • Phase: setTimeout → Timers phase
  • Phase: setImmediate → Check phase
  • Delay: setTimeout has delay
  • Delay: setImmediate runs after I/O
  • Order: Execution order is not always guaranteed

5. Example (Basic)

setTimeout(() => console.log("Timeout"), 0);

setImmediate(() => console.log("Immediate"));

👉 Output order is not guaranteed in this case.

6. Example (Inside I/O)

const fs = require("fs");

fs.readFile("file.txt", () => {
  setTimeout(() => console.log("Timeout"), 0);
  setImmediate(() => console.log("Immediate"));
});

👉 Output:

Immediate
Timeout

👉 Inside I/O cycle, setImmediate runs before setTimeout.

7. Why This is Important

  • Helps understand Event Loop deeply
  • Important for async debugging
  • Frequently asked in interviews

Interview Points

  • setTimeout runs in Timers phase
  • setImmediate runs in Check phase
  • Execution order depends on context
  • Inside I/O → setImmediate executes first