简体   繁体   English

这是使用 requestAnimationFrame 的正确方法吗?

[英]Is this the proper way to use requestAnimationFrame?

I have a piece of software that I wrote which fires repaints of the screen as soon as the updating logic is finished.我有一个我编写的软件,它会在更新逻辑完成后立即触发屏幕重绘。 The issue is that the updating logic happens over 1000 times per second.问题是更新逻辑每秒发生超过 1000 次。 The browser cannot update the screen this quickly, so I figured that a requestAnimationFrame would allow me to update the screen for the user in a slower manner.浏览器无法如此快速地更新屏幕,因此我认为 requestAnimationFrame 将允许我以较慢的方式为用户更新屏幕。

I structured the code like so:我这样构造代码:

function repaint(){
   now = Date.now();
   elapsed = now-then;
   if(elapsed > 2000){
   .
   .
   .
   //animation goes here
   .
   .
   .
   then = Date.now();
   }

}

function startRepaint(){
   then = Date.now();
   requestAnimationFrame(repaint);
}

while(count < 1000){
   .
   .
   .
   startRepaint();
   .
   .
   .
}

Can I use requestAnimationFrame in this way to achieve my desired functionality?我可以以这种方式使用 requestAnimationFrame 来实现我想要的功能吗?

What you have here is not what you're looking for.你在这里拥有的不是你想要的。

Every time you go through the while loop, you call startRepaint() which sends off a request for an animation frame.每次执行 while 循环时,都会调用startRepaint() ,它会发出对动画帧的请求。

After the first call to that function you go through the while loop and call it again.第一次调用该函数后,您将遍历 while 循环并再次调用它。 By the time you have called this function a second time, you may not have received your first animation frame yet.当您第二次调用此函数时,您可能还没有收到第一个动画帧。

Ideally, you want to set it up so that you call an update function which in turn sends the next request.理想情况下,您希望对其进行设置,以便调用更新函数,该函数又会发送下一个请求。

function repaint() {
    ...
    requestAnimationFrame(repaint);
}

Doing it this way ensures that you always complete a full frame of your code before trying to start the next one.这样做可以确保您在尝试开始下一个之前始终完成完整的代码框架。

You could use a counter variable in the repaint function to track the iterations.您可以在重绘函数中使用计数器变量来跟踪迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM