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.
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:
The syntax of Node.js Timer is given below:
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.
Timers in Node.js can be classified into two types. They are as follows:
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 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.
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:
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.
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.
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.
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.
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.
This method cancels an immediate object which is created by setImmediate(). It prevents the scheduled callback from executing.
Consider the following example:
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.
This method is utilized to cancel the timer created by setInterval(). It stops the repeating execution of the callback function.
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.
The clearTimeout() method cancels a timer previously created by setTimeout(), preventing the scheduled callback from executing.
Let’s see an example to understand this.
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.
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.
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".
The differences between setTimeout(), setInterval() and setImmediate() are as follows:
| Features | setTimeout() | setInterval() | setImmediate() |
|---|---|---|---|
| Purpose | It 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. |
| Execution | It runs only once. | It runs repeatedly until stopped. | It runs only once. |
| Delay | It 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 Method | The cancellation method of setTimeout() is clearTimeout(). | The cancellation method of setInterval() is clearInterval(). | The cancellation method of setImmediate() is clearImmediate(). |
| Use Case | It 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. |
| Returns | A Timeout object. | A Timeout object. | An immediate object. |
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().
We request you to subscribe our newsletter for upcoming updates.