Node.js Course
Node.js
/
Advanced

setImmediate()

Definition

A function that executes a callback immediately after the Event Loop's Poll phase finishes. It belongs to the Check phase of the Event Loop.

Explain Like I'm New

It's poorly named. `setImmediate` is NOT immediate. `nextTick` is immediate. `setImmediate` means: 'Hey Event Loop, after you finish dealing with all the heavy database and file operations in the Poll phase, run this code next before you loop back to the Timers.'

Real World Example

Used heavily when you have a massive array to process (like 1,000,000 items). Instead of using a `for` loop (which freezes the server), you process 1,000 items, and use `setImmediate` to process the next 1,000. This yields control back to the Event Loop, allowing it to serve HTTP requests in between chunks!

Common Use Cases

  • •CPU-intensive task chunking
  • •Preventing Event Loop starvation

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Which phase of the Event Loop executes `setImmediate` callbacks?

intermediate

  • What is the difference between `setImmediate` and `setTimeout(cb, 0)`?

advanced

  • Why is the execution order of `setImmediate` and `setTimeout(0)` sometimes unpredictable in the main module?

Flash Cards

Question

Which phase?

Click to reveal answer
Answer

The Check phase.

Question

Unpredictable execution?

Click to reveal answer
Answer

If you run both in the main script, the system performance determines which runs first. BUT, if you put them both inside an I/O callback (like `fs.readFile`), `setImmediate` will ALWAYS execute first because the Poll phase (I/O) naturally transitions directly into the Check phase (`setImmediate`) before it loops back around to Timers (`setTimeout`).