requestAnimationFrame的触发频率远高于每秒60帧

requestAnimationFrame fires far more often than 60 fps

本文关键字:高于每 60帧 频率 requestAnimationFrame      更新时间:2023-11-23

我正在使用requestAnimationFrame在mousemove上为页面的一部分设置动画。我刚才遇到的一个问题是,如果鼠标移动事件发生得比预期的每秒60次(我的监视器刷新率)快,它调用绘图代码的频率要高得多。

这似乎取决于你使用的鼠标,但使用我目前的鼠标,如果我移动得相对较快,我可以在同一帧内轻松地获得10个鼠标移动事件。我的理解是,requestAnimationFrame每个帧只应触发绘图函数一次,无论调用频率如何。

现在,在一帧内调用我的绘图代码10次显然对性能来说很糟糕,所以我需要摆脱这种情况。我必须按设计手动处理吗?我对requestAnimationFrame的理解是错误的吗?这是正确的行为,还是我在这里缺少了什么?requestAnimationFrame应该如何工作?

我的理解是,requestAnimationFrame每个帧只应触发绘图函数一次,无论调用频率如何。

这就是你的理解误导你的地方。

requestAnimationFrame方法实际上会堆叠每个函数,并在同一帧中执行它们。

所以,如果您在同一帧中调用了30次requestAnimationFrame(func),那么func将在下一帧中被调用30次。这些函数似乎甚至被合并到同一个调用中,因为它们共享相同的time参数。

var funcA = function(time) {
  snippet.log('funcA executed at ' + time);
  snippet.log('exact time: ' + performance.now())
}
var funcB = function(time) {
  snippet.log('funcB executed at ' + time);
  snippet.log('exact time: ' + performance.now())
}
snippet.log('funcA stacked at ' + performance.now())
requestAnimationFrame(funcA);
// block the process for some time
var i = 0;
while (i++ < 10000000) {}
snippet.log('funcB stacked at ' + performance.now())
requestAnimationFrame(funcB);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

为了避免这种情况,例如,为了进行反跳,您需要使用一些标记,当rAF执行时,您将释放这些标记。