如何使用 setInterval 和 clearInterval?
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
?
I want to call drawAll()
once not creating a loop that call drawAll
again and again, should I use recursive method for that or should I use clearInterval
?
还请告诉我使用 clearInterval
吗?谢谢:)
Also please tell me to use clearInterval
? Thanks :)
setInterval
设置 recurring 计时器.它返回一个句柄,您可以将其传递给 clearInterval
以阻止它触发:
setInterval
sets up a recurring timer. It returns a handle that you can pass into clearInterval
to stop it from firing:
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 的计时器函数返回一个对象.)
On browsers, the handle is guaranteed to be a number that isn't equal to 0
; therefore, 0
makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)
要安排一个函数仅触发一次,请改用 setTimeout
.它不会一直开火.(如果合适,它还会返回一个句柄,您可以在它触发一次之前通过 clearTimeout
用于取消它.)
To schedule a function to only fire once, use setTimeout
instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout
before it fires that one time if appropriate.)
setTimeout(drawAll, 20);