setInterval vs setTimeout in Node.js

In this tutorial, we will compare two functions from the timers module in Node.js.With the assistance of an example, we will learn how setInterval() and setTimeout() vary from one another.

Comparing setInterval and setTimeout

setTimeout():

It executes the code after the specified delay is over. This function takes arguments that are a call-back function and a millisecond delay. It even accepts parameters but that is optional. It is executed only once.

Example

const myFunc=(param)=>{
    console.log(param+" this will be played after 3 seconds")
}
setTimeout(myFunc,3*1000,"Hello")

Output

Hello this will be played after 3 seconds.

You can cancel your setTimeout() function with clearTimeout(). Here, the variable timerId stores the identifier(id) returned from the function.

Example:

let timerId = setTimeout(() => console.log("never prints"), 1000);
clearTimeout(timerId);
console.log("directly this is printed")

Output:

directly this is printed

setInterval():

It executes the function multiple times after a specified delay till it is stopped manually or a clearInterval() function is invoked. The function takes two arguments which are a call-back function and a millisecond delay. It is used when you want to execute a function multiple times.

Example:

let i = 0;
function num() {
  i++;
  console.log(i);
}
setInterval(num, 2000);

Output:

1
2
3
4
5
6
7
8
9
10
...

In the example given above, it will continue to print the number every 2 seconds until we manually stop it by pressing Ctrl+C.

To prevent setInterval() function from running, we can use clearInterval(). Here, the variable printNum stores an identifier(id) returned from the function.

Example

let i = 0;
function inc() {
    i++;
    console.log(i);
  
}
var printNum=setInterval(inc, 2000);
setTimeout(() => {
  clearInterval(printNum);
},5000);

Output

1
2

Here, we make use of setTimeout with clearInterval to stop setInterval after 5 seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *