Stop setInterval call in JavaScript

Stop setInterval call in JavaScript

If you want to stop the execution of setInterval function in JavaScript, you can use the clearInterval() method. It clears the interval which has been set by the setInterval() method.

Syntax

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
clearInterval(intervalID);

The clearInterval() method takes an intervalID parameter, which is the ID returned by the setInterval() method. When you call clearInterval() with the intervalID, it stops the interval from executing.

Example

var intervalID = window.setInterval(myFunc, 1000);

function myFunc() {
  console.log('Hello World!');
}

// Stop the interval after 5 seconds
setTimeout(function() {
   clearInterval(intervalID);
}, 5000);

In this example, we set an interval to execute the myFunc() function every 1 second. Then, we use the setTimeout() method to stop the interval after 5 seconds.

Another Example

function startTimer() {
  var count = 0;
  var timer = setInterval(function() {
    console.log(count);
    count++;
    if(count === 10) {
      clearInterval(timer);
    }
  }, 1000);
}
startTimer();

In this example, we create a startTimer() function that sets an interval to execute a function every 1 second. The function logs a count variable to the console and increments it by 1 on each execution. When the count reaches 10, we call clearInterval() to stop the interval.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe