Understanding setImmediate

In Bnlang, setImmediate is a function that schedules a callback to run on the check phase of the event loop.
This means it executes after I/O events but before timers scheduled with setTimeout(…, 0).
It is useful for deferring execution to the next cycle of the event loop without unnecessary delays.


Basic Example

console.log("Start");

setImmediate(() => {
  console.log("Immediate callback");
});

console.log("End");

// Output:
// Start
// End
// Immediate callback

setImmediate vs setTimeout

  • setImmediate executes callbacks in the check phase, right after I/O.
  • setTimeout(fn, 0) executes in the timers phase, which comes later.
    In practice, setImmediate usually runs faster than setTimeout(…, 0).

Example: setImmediate vs setTimeout

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

console.log("Done");

// Output order may vary:
// Done
// Immediate
// Timeout 0

Best Practices

  • Use setImmediate to break up long-running tasks and keep the event loop responsive.
  • Prefer setImmediate over setTimeout(…, 0) when you need execution as soon as the current I/O completes.
  • Avoid blocking inside callbacks to maintain performance.