Timer module in Node.js:
Most of the time, we need to execute a piece of code after a specific interval of time. For example, using a timer, we can repeat the execution of a single code block at specific time intervals. This tutorial is on Node.js and I am going to discuss a few methods that can be used to add a timer in Node.js.
The Timer module contains the functions that are used to add delay to an execution. Also, we don’t need to import this module using the require() keyword. Following are the methods we can use from the Timer module:
-
setTimeout()
-
setImmediate()
-
setInterval()
Let’s check them one by one:
Create a Node.js file:
I am assuming that you have Node.js installed on your system. If not, you can download and install it from here. We are not covering it here as the installation process is different for a different operating system.
You can use one terminal to execute a Node.js file. Create one .js file, put your code in it and run node file_path in a terminal to execute the code.
setTimeout():
This method is similar to the window.setTimeout() method. It takes one function as the first argument and time value as the second argument. The function will run after that time.
For example:
var initialTime = Date.now();
setTimeout(() => {
var finalTime = Date.now();
console.log(`time difference : ${finalTime - initialTime}`);
},1500);
In this example, we are recording the initial time before setTimeout is called. We are recording the final time after the argument function executes and we are printing the time taken for the execution or the delay.
The second argument is the time delay in milliseconds.
You may get the output as 1504,1503 etc. and not 1500 as it is not a good way to find out the delay. We are recording the time finalTime inside the function and it will take a few milliseconds to execute.
We can also add one extra third argument to this method. This will be passed to the function:
var initialTime = Date.now();
setTimeout((t) => {
var finalTime = Date.now();
console.log(`time difference : ${finalTime - t}`);
},1500,initialTime);
Here, we have passed the initialTime as the argument to setTimeout function.
Cancelling a setTimeout:
We can also cancel a setTimeout. It returns one Timeout object. We can use this object to cancel the future operation like below:
var initialTime = Date.now();
const timeOut = setTimeout((t) => {
var finalTime = Date.now();
console.log(`time difference : ${finalTime - t}`);
},1500,initialTime);
clearTimeout(timeOut);
Run it and it will quit without executing the function.
setImmediate:
This method will execute a function right after the next code blocks after the setImmediate function or at the end of the current event loop cycle. We don’t need to pass any time interval to this method. The first argument is the function to execute. You can also pass any extra arguments to this function as the above example we have seen for setTimeout
console.log('before....');
setImmediate((arg) => {
console.log(`executing....${arg}`);
}, '!!!!');
console.log('after 1....');
console.log('after 2.....');
It will print the below output:
before....
after 1....
after 2.....
executing....!!!!
It returns one Immediate object and we can use it to cancel a scheduled immediate using clearImmediate() method.
setInterval():
setInterval is used to execute a function for an infinite amount of times. Its arguments are the same as the setTimeout method. The first argument is the function to execute, the second argument is the delay in milliseconds between each execution and optionally we can add additional arguments to pass to the function as parameters.
A simple example will look like as below:
setInterval(()=> {
console.log(`tick..${Date.now()}`)
},1000);
It will keep running the function infinitely at a 1-second interval.
Similar to the setTimeout() function, it returns one Timeout object and we can use the clearInterval() method to cancel execution.