Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear interval from another function

I want to trigger a setInterval() based on a success of a particular function.

function myCountComplete(){
   //do something
   count++;
   if(count > 10){
      var myVar = setInterval(function(){ setColor() }, 300);
   }
}

function setColor() {
    var x = document.body;
    x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

How can I clear the myVar interval when a button is clicked?

$("#stop").click(function(){
    clearInterval(myVar);
});
like image 488
Bekki Avatar asked Dec 14 '22 12:12

Bekki


1 Answers

You can always set it on the global scope, i.e.

window.myTimer = setInterval(function(){ setColor() }, 300);

$("#stop").click(function(){
    clearInterval(window.myTimer);
});
like image 72
andrrs Avatar answered Feb 19 '23 22:02

andrrs