Node.js Timer

Last Updated : 31 Aug 2026

Node.js Timers are used to schedule the execution of code after a specified delay or at regular intervals without blocking the event loop. They help developers perform asynchronous tasks efficiently and control when a function executes.

What are Timers in Node.js

The timers in Node.js allow us to run a piece of code after a specified delay or at repeated intervals. We can use timers without importing them. It provides the following features:

  • It helps manage when and how often a function runs in an application.
  • It is useful for creating delays, scheduling tasks and handling asynchronous events.
  • It works with the Node.js event loop to manage timed callbacks.
  • It is commonly used in server operations, background tasks and periodic updates.

Node.js Timer Syntax

The syntax of Node.js Timer is given below:

Parameters

timerFunction: It represents a Node.js timer function such as setTimeout() or setInterval().

callback: It is the function that will be executed when the timer expires.

delay: It specifies the time (in milliseconds) before the callback function is executed.

…args: It represents optional arguments passed to the callback function when it is executed.

Types of Timers in Node.js

Timers in Node.js can be classified into two types. They are as follows:

Scheduling Timers

Scheduling timers allow functions to run after a specified delay or at repeated intervals. We use them to schedule tasks and control delayed or repeated execution of functions without blocking the event loop. They include the setImmediate() method, the setInterval() method and the setTimeout() method.

Canceling Timers

Canceling timers are utilized to stop or prevent the execution of previously scheduled timer functions. They help control time-based operations in Node.js applications. They allow scheduled timers to be canceled before they execute. They are used to prevent unnecessary or repeated executions of callbacks. They include the clearImmediate(), clearInterval() and clearTimeout() methods.

Node.js setImmediate() Method

This method schedules a callback to execute during the check phase of the next iteration of the event loop. In the setImmediate() method, the callbacks run in the order they are created after each loop iteration.

Let’s look at an example:

Code:

setImmediate(function firstFunction() {
     setImmediate(function secondFunction() {
              console.log(2);
              setImmediate(function fourthFunction() {
                     console.log(3);
              });
       });
      setImmediate(function thirdFunction() {
                      console.log(4)
                      setImmediate(function  fifthFunction() {
                            console.log(5);
                        });
            });
});
console.log("Initialized...");

Output:

Initialized…
2 
4 
3 
5

Explanation:

In this example, "Initialized…" is printed first because it is executed synchronously. The first-level setImmediate() callbacks are then executed during the check phase. The nested callbacks are scheduled for later iterations of the event loop.

Node.js setInterval() Method

This method runs a callback function repeatedly after every specified time interval in milliseconds. It keeps running until it is stopped using clearInterval().

Let’s look at an example to understand.

Code:

setInterval (function first() {
       return console.log("Hello Node.js");
}, 1000);
console.log("Execute before first function");

Output:

Execute before first function
Hello Node.js 
Hello Node.js 
Hello Node.js 
Hello Node.js 
Hello Node.js

Explanation:

In this example, the console.log("Execute before first function") is executed first because it is synchronous. The setInterval() function then executes the callback every 1000 milliseconds that repeatedly prints "Hello Node.js" until the interval is cleared using clearInterval() or the program stops.

Node.js setTimeout() Method

This method schedules a callback function to execute once after a specified delay in milliseconds.

Let’s look at an example of the setTimeout() method.

Code:

setTimeout(function first() {
      return console.log("Hello Node.js Timer");
}, 3000);
console.log("Executed before first function…")

Output:

Executed before first function… 
Hello Node.js Timer

Explanation:

In the above example, console.log("Executed before first function…") is executed first because it is synchronous. The setTimeout() function schedules the callback to run after 3000 milliseconds, after which it prints "Hello Node.js Timer" once.

Node.js clearImmediate() Method

This method cancels an immediate object which is created by setImmediate(). It prevents the scheduled callback from executing.

Consider the following example:

Code:

let fun = setImmediate(function first() {
      console.log(2);
});
//clear setImmediate fun
clearImmediate(fun);
console.log(3); 

Output:

3 

Explanation:

The setImmediate() schedules the callback function to execute during the next iteration of the event loop. However, clearImmediate(fun) cancels the scheduled callback before it executes. Therefore, only console.log(3) is executed because it is synchronous and the callback function that prints 2 is never executed.

Node.js clearInterval() Method

This method is utilized to cancel the timer created by setInterval(). It stops the repeating execution of the callback function.

Code:

let fun = setInterval(function first() {
    console.log("Hello Node.js");
}, 100);
setTimeout(function() {
        clearInterval(fun);
}, 500);

Output:

Hello Node.js 
Hello Node.js 
Hello Node.js
Hello Node.js

Explanation:

In this example, the setInterval() schedules the callback function to run every 100 milliseconds and repeatedly prints  "Hello Node.js".  After 500 milliseconds, setTimeout() calls clearInterval() to stop the interval. As a result, "Hello Node.js" is printed several times before the interval is cleared.

Note: The exact number of times the message "Hello Node.js" is printed may vary slightly depending on the event loop scheduling.

Node.js clearTimeout() Method

The clearTimeout() method cancels a timer previously created by setTimeout(), preventing the scheduled callback from executing.

Let’s see an example to understand this.

Code:

let timer1 = setTimeout(function A() {
    console.log("Hello World!");
}, 3000);

let timer2 = setTimeout(function B() {
    console.log("Hello Tpoint!");
}, 3000);

clearTimeout(timer1);

Output:

Hello Tpoint!

Explanation:

In the above example, two timers are created utilizing setTimeout(). The clearTimeout(timer1) method cancels the first timer before it executes. Therefore, only the second timer runs after approximately 3000 milliseconds.

How Node.js Timers Work with the Event Loop

Node.js Timers work with the Event Loop to execute callback functions after a specified delay without blocking the execution of other code. When the timer's delay has elapsed then its callback becomes eligible to be executed. The Event Loop executes it when the appropriate timer phase is reached and the JavaScript thread is available.

Let us look at an example.

Code:

console.log("Start");

setTimeout(() => {
    console.log("Timer Executed");
}, 2000);

console.log("End");

Output:

Start
End
Timer Executed

Explanation:

Here, the setTimeout() registers the timer with the Event Loop. Node.js continues executing the remaining code and prints "End". After 2 seconds, the event loop executes the callback and prints "Timer Executed".

Difference between setTimeout(), setInterval() and setImmediate()

The differences between setTimeout(), setInterval() and setImmediate() are as follows:

FeaturessetTimeout()setInterval()setImmediate()
PurposeIt executes a callback once after a specified delay.It executes a callback repeatedly after a specified interval.It schedules a callback to execute during the check phase of the event loop.
ExecutionIt runs only once.It runs repeatedly until stopped.It runs only once.
DelayIt accepts a delay in milliseconds.It accepts a time interval in milliseconds.It does not accept a delay parameter and the callback is scheduled for the check phase.
Cancellation MethodThe cancellation method of setTimeout() is clearTimeout().The cancellation method of setInterval() is clearInterval().The cancellation method of setImmediate() is clearImmediate().
Use CaseIt delays the execution of a task.It runs periodic or recurring tasks.It schedules a callback to execute during the check phase of the event loop, typically after I/O callbacks.
ReturnsA Timeout object.A Timeout object.An immediate object.

Why use Timers in Node.js

Node.js timers provide the following benefits:

Delay code execution

It runs a function after a specified delay using setTimeout().

Run recurring tasks

It performs repeated operations at specified intervals using setInterval().

Schedule immediate callbacks

It executes a callback during the check phase of the next event loop iteration.

Handle asynchronous operations

It performs non-blocking tasks while allowing the application to continue executing other code.

Cancel scheduled tasks

It stops pending or recurring timers utilizing the clearTimeout(), clearInterval(), and clearImmediate().


Next TopicNode.js Errors