Timers

In Node.js, the Timers module provides global functions to schedule the execution of code at a later point in time. Because these functions are global, you don't need to require('timers') to use them.

Unlike browser-based timers, Node.js timers are built on top of the Event Loop and behave slightly differently regarding execution priority.


1. The Three Main Timers


A. setTimeout()

Schedules a one-time execution after a specified delay in milliseconds.

  • Best for: Delaying an action or setting a timeout for a network request.


setTimeout((name) => {
  console.log(`Hello, ${name}!`);
}, 2000, 'Tharun'); // 2 seconds delay


B. setInterval()

Schedules repeated execution of code every time a specific interval passes.

  • Best for: Polling a database, heartbeats in a TCP connection, or updating a UI clock.


const intervalId = setInterval(() => {
  console.log('Checking server status...');
}, 5000);

// To stop it:
// clearInterval(intervalId);

C. setImmediate()

Schedules the "immediate" execution of a callback after the current Event Loop cycle completes.

  • Best for: Breaking up long-running synchronous operations to allow the Event Loop to handle other I/O events.


2. process.nextTick() vs setImmediate()


This is a frequent source of confusion. They control when a callback enters the execution phase.

  • process.nextTick(): Executes immediately after the current operation finishes, before the Event Loop continues. It's like cutting to the front of the line. If used recursively, it can "starve" the Event Loop (preventing I/O from ever happening).

  • setImmediate(): Executes in the Check phase of the next iteration of the Event Loop. It's like standing at the very end of the line for the next round.


3. Promisified Timers (Modern Node.js)


In modern development, using callbacks for timers can lead to "callback hell." Node.js provides a promise-based version of timers that works perfectly with async/await.


const { setTimeout } = require('node:timers/promises');

async function runTask() {
  console.log('Waiting...');
  await setTimeout(2000); // Wait 2 seconds
  console.log('Done!');
}


4. Technical Truths about Accuracy


  1. No Guarantee: The delay you specify is the minimum time, not the exact time. If the Event Loop is busy with a heavy CPU task (like a large loop or complex math), your setTimeout(1000) might actually take 1050ms or more to fire.

  2. Zero Delay: setTimeout(callback, 0) is effectively the same as setTimeout(callback, 1). It doesn't run "instantly"—it still has to wait for the next loop.


5. Managing Memory (Clearing Timers)


Every timer returns an object that can be used to cancel the timer. If you don't clear an interval that is no longer needed, your Node.js process will stay alive indefinitely, and you may encounter memory leaks.

  • clearTimeout(timeoutObj)

  • clearInterval(intervalObj)

  • clearImmediate(immediateObj)

The .unref() and .ref() Methods

If you have a timer running (like a background monitor) but you don't want it to keep the Node.js process active if it's the only thing left running, you can use .unref():


const timer = setTimeout(() => {
  console.log('This will not keep the process alive.');
}, 100000);

timer.unref(); // The script will exit even if this hasn't fired yet.


.