Asked 3 years ago
18 Nov 2020
Views 800

posted

clearInterval() Method in javascript

how clearInterval() method work ?
how to use clearInterval() method ?
steave

steave
answered Nov 30 '-1 00:00

clearInterval() to stop the running of the setInterval()

setInterval() run the specific set of code or function in given interval
to stop running the setinterval() , clearInterval() can be used


var intr = setInterval(setColor, 1000);
var i=0;
function setColor() {
 console.log(i);
if(i==2){
  clearInterval(intr);
}
i++
}


it will print


0
1
2 

at if(i==2){ it run clearInterval(intr); and stop the running of the setInterval

jassy

jassy
answered Apr 27 '22 00:00

Example of clearInterval() method :

const interval1 = setInterval( alert('me keep running until clearInterval clear me'), 500);
 setTimeout(clearInterval(interval1), 5000);

setInterval() method set alert at every 500 milisecond.
it keep buzzing until 5000 milisecond , because setTimeout run clearInterval() method after 5000 milisecond.
ravi

ravi
answered Apr 27 '22 00:00

Example of clearInterval() method :
keep changing the HTML body background color until click at anywhere in the page by clearInterval() and setInterval() method


const ChangeBodyColorintervalid = setInterval(ChangeBodyColor, 500);
function ChangeBodyColor() {
                  document.body.style.backgroundColor = (  document.body.style.backgroundColor == "red" ? "black" : "red");
}

document.body.addEventListener("click", function () {
     clearInterval(ChangeBodyColorintervalid);
}, false);
 
fatso

fatso
answered Apr 27 '22 00:00

clearInterval is the function used to cancle the previously called setInterval() iteration

clearInterval(intervalId)


clearInterval has one parameter. which is required.
The interval id returned from setInterval().
Post Answer