如何使用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
设置重复出现计时器。它返回一个句柄,您可以将其传递到 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
为no timer set设置一个方便的标志值。 (其他平台可能返回其他值;例如,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);