Javascript 有没有办法通过 Onclick 按钮杀死 setInterval 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2790815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:56:08  来源:igfitidea点击:

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

javascriptonclickinfinite-loopsetinterval

提问by JoeOzz

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 intervalsthrough an onClick?

因此,我使用附加到 onClick 的 setInterval 获得了一个无限循环来处理此函数。问题是,我无法在 onClick 中使用 clearInterval 来阻止它。我认为这是因为当我将 clearInterval 附加到 onClick 时,它会杀死特定的间隔而不是完全的函数。我可以做些什么来通过 onClick杀死所有间隔

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

这是我的.js 文件,我正在进行的调用是

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.

回答by house9

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

setInterval 返回一个句柄,您需要该句柄以便清除它

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

最简单的方法,在你的 html 头中为句柄创建一个 var,然后在你的 onclick 中使用 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

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

回答by kennytm

clearIntervalis applied on the return value of setInterval, like this:

clearInterval应用于 的返回值setInterval,如下所示:

var interval = null;
theSecondButton.onclick = function() {
    if (interval === null) {
       interval = setInterval(generation, 1000);
    }
}
theThirdButton.onclick = function () {
   if (interval !== null) {
       clearInterval(interval);
       interval = null;
   }
}

回答by Diodeus - James MacFarlane

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

generation();电话setTimeout来本身,而不是setInterval。那就是你可以在函数中使用一些 if 逻辑来防止它setTimeout很容易地运行。

var genTimer
var stopGen = 0

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

}

}