Javascript 定时器延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13994910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:25:25  来源:igfitidea点击:

Javascript timer delay

javascripttimerhtml5-canvasdelay

提问by Katherine1

I've decided to play around with HTML5's canvas, and of course that means I'm going to try writing a pong game. At the moment, I am trying to figure out how to cap my framerate. This is fairly easy in other languages, but finding a way to delay execution in Javascript seems to be a bit tougher.

我决定尝试使用 HTML5 的画布,当然这意味着我将尝试编写乒乓球游戏。目前,我正试图弄清楚如何限制我的帧率。这在其他语言中相当容易,但在 Javascript 中找到一种延迟执行的方法似乎有点困难。

Here is what I have so far:

这是我到目前为止所拥有的:

while(true) {
    var begin = (new Date()).getTime();

    //Draw stuff to the canvas

    var end = (new Date()).getTime();
    if ((end-begin) < 33.333 ) {
        //delay (1000/(30-(end-begin)))
    }
}

Obviously, frame rates will be wildly different due to how each javascript engine performs, but I want to cap the maximum framerate at 30FPS. I don't really see how setTimeout() would accomplish this task. What would be the best way to do this?

显然,由于每个 javascript 引擎的执行方式,帧速率会大不相同,但我想将最大帧速率限制在 30FPS。我真的不明白 setTimeout() 将如何完成这项任务。什么是最好的方法来做到这一点?

回答by closure

There is no delay/ waitin JavaScript. You can use functions like window.setTimeoutto call a function after certain time has elapsed, example:

JavaScript 中没有delay/ wait。您可以使用函数window.setTimeout,例如在经过特定时间后调用函数,例如:

window.setTimeout(function() {
    // do something interesting
}, 2000 /* but after 2000 ms */);

Or say you want to paint a frame every 33 ms (~30 fps), you will code it like:

或者说你想每 33 毫秒(~30 fps)绘制一个帧,你可以这样编码:

window.setInterval(function() {
    // paint my frame 
}, 33);