How to stop setInterval call in JavaScript

In this article, we will learn how can we stop the setInterval() method after invoking it. This method is used to call the function specified repeatedly after the given time interval. We will look at the example and see how we can stop this function.

Stopping setInterval call in JavaScript

setInterval() method continues to run until the window is closed or it is stopped manually using clearInterval() method. The setInterval () method returns a unique ID that identifies the interval. On passing that ID to the clearInterval() we can stop or cancel the method.

Example 1:

let count=0;
let timerID = setInterval(function(){
  count=count+1;
    if(count === 10){
        clearInterval(timerID);
    }
    let date= new Date();
    let timing = date.toLocaleTimeString();
    console.log(timing);

}, 3000);

Output:

Here, we declare a count variable that will count the number of times the function will run and when the count reaches the number 10 it will stop the setInterval() method. The time is printed every 3 seconds till it is stopped.

Example 2:

index.html

<html>  
<head>  
<title> Stop </title>  
</head>  
<body>  
<h1> Codespeedy</h1>  
<p> The background color will change every 3000 milliseconds. </p>  
<p>On clicking,stop the changing will Stop</p>
<button onclick = "stopping()"> Stop </button>  
  
<script>  
var interval = setInterval(color, 200);  
  
function color() {  
var background1 = document.body;  
background1.style.backgroundColor = background1.style.backgroundColor == "red" ? "green" : "red";  
}  
function stopping() {  
clearInterval(interval);  
}  
  
</script>  
  
</body>  
  
</html>

Output:

setInterval()

stop setInterval()

Here, the background color will change every three seconds or 3000 milliseconds until we will click on the stop button that will trigger the stopping function. In the stopping method, we apply clearInterval()  to the interval variable resulting in setInterval() to stop.

Leave a Reply

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