7

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);
});
Bekki
  • 719
  • 2
  • 12
  • 20
  • 3
    Have `myVar` as a global variable. ie declare it (`var myVar`) outside of the functions. – Andy Aug 12 '15 at 12:26

4 Answers4

13

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

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

$("#stop").click(function(){
    clearInterval(window.myTimer);
});
andrrs
  • 2,289
  • 3
  • 17
  • 25
5

"window" is not necessary, and my opinion is that is bad practice to use it. Just remove "var" and scope will be automatically global.

http://www.w3schools.com/js/js_scope.asp

Implant
  • 96
  • 5
1

This is a scope issue.
See What is the scope of variables in JavaScript?

Basically, declare the myVar into a scope available in both case. For instance:

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

$("#stop").click(function(){
    clearInterval(window.myVar);
});
Community
  • 1
  • 1
ben
  • 3,558
  • 1
  • 15
  • 28
1

I had a similar issue so I just moved the setInterval to a global scope and added a check to it so that whatever code that was to be implemented in each interval would only be implemented if the check is successful, else the interval would do nothing.

const someInterval = setInterval(() => {
  if (checkSuccessful) {
    // Do something.
  }
  // Do nothing.
}, 1000);

clearInterval(someInterval);
Manil Malla
  • 133
  • 8