如何确定在JavaScript动画循环中使用的最佳"帧速率"(setInterval延迟)?

Ric*_*ket 26 javascript jquery

编写JavaScript动画时,您当然会使用setInterval(或重复的setTimeout)进行循环.但是在setInterval/setTimeout调用中使用的最佳延迟是什么?

.animate()函数jQuery API页面中,用户"fbogner"说:

如果有人感兴趣:动画是使用setInterval"渲染"的,时间超过13毫秒.这很快!Chrome的最快间隔时间约为10毫秒.所有其他浏览器在20-30ms左右"采样".

知道jQuery如何决定使用这个特定的数字吗?


开始赏金.我希望有了解Chromium或Firefox背后的源代码的人可以提供一些可能支持特定帧速率决策的硬性事实.或者可能是动画(或框架)列表及其延迟.我相信这为进行一些研究提供了一个有趣的机会.


有趣 - 我只是花时间看看谷歌的吃豆人来源,看看他们做了什么.他们设置了一系列可能的FPS(90,45,30),从第一个开始,然后每帧检查帧的"慢度"(帧的数量超过其分配的时间).如果慢度超过50ms 20次,则帧速率下降到列表中的下一个(90 - > 45,45 - > 30).看起来帧速率永远不会提升,大概是因为游戏的寿命很短,所以编码就不值得了.

哦,setInterval延迟当然设置为1000 /帧速率.事实上,它们使用setInterval而不是重复的setTimeouts.

我认为这种动态帧率功能非常整洁!

Lon*_*ang 17

我冒昧地说,相当一部分网络用户正在使用以60Hz刷新的监视器,这意味着每16.66ms转换一帧.因此,要使显示器成为瓶颈,您需要生成速度超过16.66ms的帧.

你选择一个像13ms这样的值有两个原因.首先,浏览器需要一点时间来重新绘制屏幕(根据我的经验,从不低于1毫秒).例如,每隔15毫秒更新一次,这恰好是一个非常有趣的数字 - Windows上的标准计时器分辨率是15毫秒(参见John Resig的博客文章).我怀疑在各种浏览器/操作系统上,写得很好的15ms动画看起来非常接近.

FWIW,fbogner严重错误的是非Chrome浏览器每20-30ms触发一次setInterval.我写了一个测试来测量setInterval触发的速度,并获得了这些数字:

  • Chrome - 4ms
  • Firefox 3.5 - 15ms
  • IE6 - 15ms
  • IE8 - 15ms


INS*_*INS 5

这个伪代码是这样的:

FPS_WANTED = 25 
(just a number, it can be changed while executing, or it can be constant)

TIME_OF_DRAWING = 1000/FPS_WANTED 
(this is in milliseconds, I believe it is accurate enough) 
( should be updated when FPS_WANTED changes)

UntilTheUserLeavesTheDrawingApplication()
{

  time1 = getTime();
  doAnimation();
  time2 = getTime();
  animationTime = time2-time1;

  if (animationTime > TIME_OF_DRAWING)
  {
     [the FPS_WANTED cannot be reached]
     You can:
     1. Decrease the number of FPS to see if a lower framerate can be achieved
     2. Do nothing because you want to get all you can from the CPU
  }
  else
  {
     [the FPS can be reached - you can decide to]
     1. wait(TIME_OF_DRAWING-animationTime) - to keep a constant framerate of FPS_WANTED
     2. increase framerate if you want
     3. Do nothing because you want to get all you can from the CPU
  }

}
Run Code Online (Sandbox Code Playgroud)

当然可以有各种变化,但这是在任何动画情况下都有效的基本算法.