How to Clear Interval in JavaScript

To clear an interval in JavaScript, use the clearInterval() function and pass the interval object as the first argument.

 

JavaScript Stop Interval Example

The example below demonstrates running a function in an interval using the setInterval() then stopping it.

 

var myInterval = setInterval(function(){console.log("foo")}, 2000);

clearInterval(myInterval); //stop the interval

 

The above isn't a practical example as the interval is stopped before it even completes the first iteration.

 

To make it work as intended, increment an iteration count and run clearInterval() when a condition is met:

 

var iteration = 0;

var myVar = setInterval(myCount, 1000, iteration);

function myCount() {

iteration += 1

if (iteration == 5) {
   clearInterval(myVar);
   console.log('finished!');
  }
}