5

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

3 Answers3

11

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,239
  • 3
  • 16
  • 25
2

"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
  • 56
  • 4
0

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,527
  • 1
  • 14
  • 28