如何使用 setInterval 和 clearInterval? [英] How to use setInterval and clearInterval?

查看:43
本文介绍了如何使用 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);

这篇关于如何使用 setInterval 和 clearInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆