Timers

In Node.js, Timers are a set of global functions used to schedule the execution of code at a specific time in the future. They are not part of the core JavaScript language itself but are implemented by the Node.js runtime to interact with the Event Loop.

1. Core Timer Functions


setTimeout(callback, delay, ...args)

Schedules a one-time execution of a callback after delay milliseconds.

  • Accuracy: The delay is a minimum threshold. If the Event Loop is busy with other tasks, the timer might take longer than specified.

  • Args: You can pass additional arguments that will be sent to the callback.


setTimeout((name) => {
  console.log(`Hello, ${name}`);
}, 2000, "Developer"); 
// Prints "Hello, Developer" after at least 2 seconds.

setInterval(callback, delay, ...args)

Schedules repeated execution of a callback every delay milliseconds.

  • Usage: Best for recurring tasks like "heartbeats" for a server or refreshing data.


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


2. Clearing Timers

To stop a timer from running, you must use its corresponding "clear" function. Every timer function returns an object (the "Timeout" or "Interval" object) that can be passed to a clearer.


const timer = setTimeout(() => console.log("Won't run"), 1000);
const interval = setInterval(() => console.log("Repeating"), 1000);

clearTimeout(timer);
clearInterval(interval);



3. The Timer Phase in the Event Loop


The Event Loop has a dedicated Timers Phase.

  1. Entry: When the loop enters the Timer phase, it checks the heap of active timers.

  2. Comparison: It compares the current time with the "expiry time" of the timers.

  3. Execution: If a timer has expired, its callback is moved to the queue to be executed.

  4. Transition: Once the queue is empty or a limit is reached, the loop moves to the next phase (I/O).


4. Advanced Timer Methods


unref() and ref()

Normally, a Node.js process will stay alive as long as there is an active timer (like an interval). Using unref() allows the process to exit even if the timer is still active.

const myTimer = setTimeout(() => {
  console.log("This might not run if the app finishes other tasks first.");
}, 10000);

myTimer.unref(); // The process won't wait 10 seconds just for this timer.


Timers with Promises (Modern Node.js)

In modern Node.js versions, you can use a promise-based version of timers. This is very useful when combined with async/await.


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

async function waitAndRun() {
  console.log("Starting...");
  await setTimeout(2000); // Pauses execution for 2 seconds
  console.log("Finished waiting!");
}

waitAndRun();


5. setTimeout(0) vs setImmediate()


This is a common interview and technical question:

  • setTimeout(0): Schedules a task for the next iteration of the Timers phase.

  • setImmediate(): Schedules a task for the Check phase, which happens right after I/O.

If you call both in the main script, the order is non-deterministic (it depends on process performance). However, if you call them inside an I/O callback (like fs.readFile), setImmediate() will always run first because the Check phase follows the Poll phase.