requestAnimationFrame在函数的开头或结尾? [英] requestAnimationFrame at beginning or end of function?

查看:101
本文介绍了requestAnimationFrame在函数的开头或结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个使用requestAnimationFrame的循环:

If I have a loop using requestAnimationFrame like this:

function render() {
    // Rendering code

    requestAnimationFrame(render);
}

如果我把 requestAnimationFrame放一点会有什么不同吗在函数的开头,如下所示:

Will there be any difference if I put the requestAnimationFrame in the beginning of the function, like this:

function render() {
    requestAnimationFrame(render);

    // Rendering code
}

我还没有注意到有任何不同,但我看到两种实现方式,其中一种更好,或者它们是否相同?

I haven't noticed any difference, but I have seen both implementations, is one of them better in any way, or are they the same?

编辑:
我有一件事已经考虑过了,如果我把它放在开头,并且渲染代码需要很长时间才能运行,比如10ms,最终不会把它放到帧速率下降10ms?

One thing I have thought about is, if I put it in the beginning, and the render code takes quite long time to run, say 10ms, wouldn't putting it in the end make the frame rate drop with 10ms?

推荐答案

requestAnimationFrame 总是异步调用它的回调,所以只要你的渲染代码是同步的,不抛出异常它没有任何区别。

requestAnimationFrame does always call its callback asynchronously, so as long as your rendering code is synchronous and does not throw exceptions it doesn't make any difference.

它本质上是一种风格选择,选择自己哪种方法更清洁。将它置于顶部可能会强调 render 正在自行调度,即使渲染中存在错误也会这样做。将其置于底部允许有条件地突破渲染循环(例如,当您想要暂停游戏时)。

It's essentially a style choice, choose yourself which approach is cleaner. Putting it at the top may emphasise that render is scheduling itself, and does so even in the presence of errors in the rendering. Putting it in the bottom allows to conditionally break out of the rendering loop (e.g. when you want to pause your game).

这篇关于requestAnimationFrame在函数的开头或结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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