views:

229

answers:

3

Hey folks. 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.

A: 

Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.

var genTimer
var stopGen = 0

function generation() {
   clearTimeout(genTimer)  ///stop additional clicks from initiating more timers
   . . .
   if(!stopGen) {
       genTimer = setTimeout(function(){generation()},1000)
   }
}

}

Diodeus
+1  A: 

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;
   }
}
KennyTM
+3  A: 

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

house9