node.js: how to use setInterval and clearInterval?

Using setInterval()

What if you need to repeat the execution of your code block at specified intervals? For this, Node has methods called setInterval() and clearInterval(). The setInterval() function is very much like setTimeout(), using the same parameters such as the callback function, delay, and any optional arguments for passing to the callback function.

A simple example of setInterval() appears below:

var interval = setInterval(function(str1, str2) {
  console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");

clearInterval(interval);

This is another way when you want to keep only one interval running every minute

function intervalFunc() {
    console.log("Hello!!!!");
     }
    setInterval(intervalFunc,1500);

In the above example, intervalFunc() will execute about every 1500 milliseconds, or 1.5 seconds, until it is stopped . Hope this helps.

Leave a Comment