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

喜欢而已 提交于 2019-12-03 16:54:06

问题


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.

回答1:


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




回答2:


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;
   }
}



回答3:


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)
   }
}

}



来源:https://stackoverflow.com/questions/2790815/is-there-any-way-to-kill-a-setinterval-loop-through-an-onclick-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!