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(){
    if(count === 10){
    let date= new Date();
    let timing = date.toLocaleTimeString();

}, 3000);


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:


<title> Stop </title>  
<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>  
var interval = setInterval(color, 200);  
function color() {  
var background1 = document.body; = == "red" ? "green" : "red";  
function stopping() {  



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 *