Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to kill a setInterval loop through an Onclick button

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?

Here's my .js file and the calls I'm making are

input type="button" value="generate" onClick="generation();

input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"

input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
like image 936
JoeOzz Avatar asked May 07 '10 18:05

JoeOzz


2 Answers

setInterval returns a handle, you need that handle so you can clear it

easiest, create a var for the handle in your html head, then in your onclick use the var

// in the head
var intervalHandle = null;

// in the onclick to set
intervalHandle = setInterval(....

// in the onclick to clear
clearInterval(intervalHandle);

http://www.w3schools.com/jsref/met_win_clearinterval.asp

like image 103
house9 Avatar answered Oct 21 '22 21:10

house9


clearInterval is applied on the return value of setInterval, like this:

var interval = null;
theSecondButton.onclick = function() {
    if (interval === null) {
       interval = setInterval(generation, 1000);
    }
}
theThirdButton.onclick = function () {
   if (interval !== null) {
       clearInterval(interval);
       interval = null;
   }
}
like image 40
kennytm Avatar answered Oct 21 '22 21:10

kennytm