因此,我使用附加到一个setInterval的onClick来执行这个函数的无限循环。问题是,我无法停止在clearInterval中使用onClick。我认为这是因为当我将一个clearInterval附加到一个onClick时,它会杀死一个特定的间隔,而不是完全杀死这个函数。通过一个onClick,我能做些什么来消除所有的间隔吗?
这是我的.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.发布于 2010-05-07 18:42:09
setInterval返回一个句柄,您需要这个句柄才能清除它。
最简单的方法是为html头中的句柄创建一个var,然后在onclick中使用var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);clearinterval.asp
发布于 2010-05-07 18:41:41
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;
   }
}发布于 2010-05-07 18:39:45
让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)
   }
}}
https://stackoverflow.com/questions/2790815
复制相似问题