JavaScript

How to Effectively Use setInterval() in Node.js?

In Node.js, the built-in “setInterval()” method executes the code block for infinite times after a specified time interval. This method helps in scheduling the program by performing the common task continuously after a particular delay as per requirements. It performs the defined task with the help of the callback function. Once the desired task is defined in the callback function, then it will automatically execute infinitely without the user’s involvement.

This post will explain the effective use of setInterval() in node.js.

What is the Use of the “setInterval()” Method in Node.js?

The “setInterval()” method is used for the execution of a code block repeatedly after the specified time delay. It performs the defined task repeatedly after the specified time interval until the user does not stop its execution using the “clearInterval()” method.

Syntax
The use of the “setInterval()” method depends on its generalized syntax which is written below:

const intervalId = setInterval(func, [delay, arg1, agr2, ..., argN]);

The above “setInterval()” method works on the following parameters:

  • func: It denotes a callback function that executes repeatedly for an infinite number of times after the specified time interval.
  • delay: It specifies no of milliseconds after which the defined callback function will execute.
  • arg1, arg2,…argN: It represents the additional arguments that pass to the specified callback function.

Return Value: The “setInterval()” returns a non-zero “intervalId” that the user can pass to another “clearInterval()” method to stop the infinite execution of the callback function.

Let’s use the above-defined method practically.

Example 1: Use the “setInterval()” Method to Execute a Function to Infinite Times
This example applies the “setInterval()” method to execute a function to infinite times:

const setTimeID = setInterval(myFunc, 1000);
function myFunc() {
 console.log("Welcome to Linuxhint!")
}

In the above code snippet:

  • The “setTimeID” variable utilizes the “setInterval()” method to execute the given callback function after the specified delay.
  • In the callback function definition, the “console.log()” method displays the quoted statement infinite times in the console after the given time interval.

Note: Write the above code lines into the “.js” file of the Node.js project.

Output
Now, initiate the “.js” file using the “node” keyword:

node app.js

It can be seen that the output displays the specified text statement repeatedly after the specified time delay:

Example 2: Use the “setInterval()” Method to Execute a Function to Finite Times
This example utilizes the “setInterval()” method to execute a function to finite times:

let count=0;
const setTimeID = setInterval(myFunc, 1000);
function myFunc() {
 console.log("Linuxhint!");
count++;
if (count === 4) {
 console.log('\nGiven Interval has been stopped after 4th executions\n');
 clearInterval(setTimeID);
 }
}

In the above lines of code:

  • Firstly, the “let” keyword declares the “count” variable with a numeric value.
  • Next, the “setInterval()” method executes the specified function after the given delay.
  • In this function, the “console.log()” method prints the specified statement in the console.
  • After that, increment the “count” variable using the “count++” statement.
  • Now, the “if” statement defines a code block in which the “console.log()” method will display the given statement, and the “clearInterval()” with the returned id of the “setInterval()” method will stop the execution of the function when the “if” condition is satisfied.

Output
Execute the “.js” file using the following command:

node app.js

It can be observed that the particular function is executed for a limited number of times:

Example 3: Use “setInterval()” Method With Arguments
This example uses the “setInterval()” method along with the parameters that are passed to the specified callback function:

let count=0;
const setTimeID = setInterval(myFunc, 1000, "Linuxhint");
function myFunc(arg) {
 console.log("Hello " + arg);
count++;
if (count === 4) {
 console.log('\nGiven Interval has been stopped after 4th executions\n');
 clearInterval(setTimeID);
 }
}

In the above code lines:

  • The “setInterval()” method specifies an argument next after the “delay” parameter.
  • In the callback function, the specified argument is passed with the help of the “arg” argument.
  • After that, the “console.log()” method prints the value of the passed argument along with the quoted string.

Output
Run the “.js” file:

node app.js

Here, the output shows the callback function is executed for finite times displaying the argument value along with the specified string in the console:

What are the Differences Between setTimeout() and setInterval()?

This section highlights the key differences between the “setTimeout()” and the “setInterval()” method:

</tr

Terms SetTimeout() SetInterval()
Objective The “setTimeout()” method executes the required code block after the specified delay(ms), only once. The “setInterval()” method executes the desired code block to infinite times after the specified time interval or “delay”.
Syntax setTimeout(callback func, delay(ms)) setInterval(callback func, delay(ms))
No. of Executions This method executes the callback function only one time after the given delay. This method executes the callback function an unlimited number of times until its execution does not stop using the “clearInterval()”.
Clear Interval It uses the “clearTimeout()” method to stop the specified function execution. It applies the “clearInterval()” method to stop the callback function execution.

That is all about the use of setInterval() in Node.js.

Conclusion

To effectively use the “setInterval()” method in Node.js, define the callback function as its parameter that performs the defined task repeatedly after a fixed delay. The execution of the defined callback function never stops automatically until the user does not stop it using the “clearInterval()” method. Moreover, this method can also be used for retrieving the variable values infinite times after the given delay. This post has practically explained the effective use of setInterval() in Node.js.

About the author

Areej Nadeem

I am a technical author holding a Bachelor’s degree in Computer Science. I am passionate about writing and learning new technologies and sharing my knowledge with the rest of the world.