Node.js Timers - setTimeout, setInterval, setImmediate & process.nextTick Compared

One of the most common points of confusion in Node.js is knowing when to use setTimeout(), setInterval(), setImmediate(), and process.nextTick(). Each executes at a different priority level within the Libuv Event Loop.

Comparison of Asynchronous Scheduling Primitives

Function Loop Execution Phase Execution Timing Common Use Case
process.nextTick() Microtask Queue (Drained between phases) Immediate (Before next loop phase) Clean error handling before I/O, emitting events after construction.
Promise.then() Microtask Queue (After nextTick) Immediate (Before next loop phase) Standard asynchronous Promise resolutions.
setTimeout(fn, ms) Timers Phase After minimum ms delay Delayed execution, timeouts, polling intervals.
setImmediate(fn) Check Phase Immediately after Poll phase Executing code after I/O finishes without waiting for timers.

setImmediate vs setTimeout Inside I/O Callbacks

When executed in the root script, the execution order between setTimeout(fn, 0) and setImmediate() can vary based on OS thread scheduling. However, when called inside an I/O callback, setImmediate is 100% deterministic:

const fs = require('fs');

fs.readFile(__filename, () => {
  // We are currently in the Poll Phase!
  setTimeout(() => {
    console.log('2. setTimeout (Timers Phase)');
  }, 0);

  setImmediate(() => {
    console.log('1. setImmediate (Check Phase)');
  });
});

Output:

1. setImmediate (Check Phase)
2. setTimeout (Timers Phase)

Why? The I/O callback finished in the Poll Phase. The very next phase in the Libuv cycle is the Check Phase, where setImmediate executes. The Timers phase is not reached until the loop cycles all the way back around!

Using timer.unref() for Non-Blocking Background Tasks

// Keep alive monitoring ping
const pingTimer = setInterval(() => {
  console.log('[Ping] Server telemetry running...');
}, 5000);

// Allow the process to exit cleanly when main server closes
pingTimer.unref();

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the primary difference between setImmediate() and setTimeout(fn, 0)?

setTimeout(fn, 0) is queued in the Timers phase and checks if at least 1 millisecond has elapsed. setImmediate() is designed to execute immediately after the Poll phase in the Check phase. When called inside an I/O callback (e.g. fs.readFile), setImmediate() is always guaranteed to execute before setTimeout.

Q2. What is Event Loop Starvation and how does process.nextTick() cause it?

Event Loop Starvation occurs when asynchronous tasks completely prevent the loop from processing I/O or timers. Because Node drains the entire nextTick queue before moving to any other phase, recursively calling process.nextTick() indefinitely starves the event loop, causing the server to freeze.

Q3. What do timer.unref() and timer.ref() do in Node.js?

Calling 'timer.unref()' tells Node.js not to keep the event loop active solely for that timer. If there are no other active handles or network listeners, the process will exit cleanly even if the timer has not finished.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Libuv Event Loop Phases

See where Timers and Check phases reside.

Callbacks & Callback Hell

Understand asynchronous callback execution.

Performance Profiling

Diagnose event loop lag caused by nextTick abuse.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!