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

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

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

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