如何使用setInterval和clearInterval?


138
function doKeyDown(event) {
    switch (event.keyCode) {
    case 32:
        /* Space bar was pressed */
        if (x == 4) {
            setInterval(drawAll, 20);
        }
        else {
            setInterval(drawAll, 20);
            x += dx;
        }
        break;
    }
}

大家好,

我想调用drawAll()一次,而不创建一次又一次调用的循环drawAll我应该为此使用递归方法还是应该使用clearInterval

还请告诉我用clearInterval?谢谢 :)

Answers:


210

setInterval设置一个定期计时器。它返回一个句柄,您可以将其传递clearInterval来阻止它触发:

var handle = setInterval(drawAll, 20);

// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval

在浏览器上,保证句柄是一个不等于0; 的数字。因此,0为“未设置定时器”设置一个方便的标志值。(其他平台可能返回其他值;例如,NodeJS的计时器函数返回一个对象。)

要将功能调度为触发一次,请setTimeout改用。它不会继续射击。(它还会返回一个句柄clearTimeout,如果合适的话,可以在触发一次之前使用它来取消它。)

setTimeout(drawAll, 20);

29

clearInterval是一种选择:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

7
切勿将字符串与setInterval或一起使用setTimeout
TJ Crowder

1
您的意思是我应该删除doStuff()周围的引号?
约书亚-Pendo,

9
是的,双引号和括号。只需:setInterval(doStuff);。将字符串传递到setInterval是对的隐式调用eval。最好改为传递函数引用
TJ Crowder

1
嗯,不好意思,也许是公平的。我展示了一个不正确的示例(尽管在我的情况下是可行的,但正如我们所说的,我正在更改它们)。竖起大拇指!:)
约书亚-Pendo

10

使用setTimeout(drawAll, 20)代替。那只会执行一次功能。


非常感谢,但是setTimeout在每个点上都完成了循环,我使用了其他方法,并且工作正常,函数doKeyDown(event){switch(event.keyCode){情况32:/ *按下空格键* / loop = setInterval (drawAll,20); 如果(x == 202){x = 400; spinner(); }; }
拉吉(Raj)

这不是问题
NinoŠkopac18年

8

我把角与电子结合使用

就我而言 setInterval返回一个Nodejs Timer对象。当我打电话时clearInterval(timerobject)它不起作用。

我必须先获取ID并调用clearInterval

clearInterval(timerobject._id)

我为此付出了很多努力。希望这可以帮助。


5

旁注–如果要使用单独的功能来设置和清除间隔,则必须在“相对全局”或“一级升级”范围内对所有变量都可以访问interval变量:

var interval = null;    

function startStuff(func, time) {
    interval = setInterval(func, time);
}

function stopStuff() {
    clearInterval(interval);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.