setInterval 和 requestanimationframe 之间有什么区别?

Moh*_*mad 3 javascript

我需要你的帮助,我有点困惑。

我的问题是 JavaScript 中的setIntervalrequestanimationframe之间有什么区别,以及何时何地使用它们?

Guf*_*ffa 7

requestAnimationFrame方法用于将动画与屏幕更新同步。屏幕以特定速率更新,例如每秒 60 次。如果您同步动画更新以使其以该速率发生,则动画看起来会很流畅。

这是一个示例,其中anim1以屏幕速率anim2运行,而以固定速率运行。如果您运行演示,您会看到左边的方块平滑地移动,而右边的方块在运动中有点跳跃。

您可以setInterval更频繁地运行以使其更流畅,但要使其支持所有不同的屏幕,您必须使其运行速度超过每秒 120 次,这比大多数屏幕所需的 CPU 多得多,有些浏览器甚至不支持那么快的速率。

window.requestAnimationFrame(anim1);

window.setInterval(anim2, 25);

var a1 = document.getElementById('a1');
var a2 = document.getElementById('a2');
var t2 = 0;

function anim1(t1) {
    a1.style.left = (50 + Math.cos(t1 / 500) * 30) + 'px';
    a1.style.top = (50 + Math.sin(t1 / 500) * 30) + 'px';
    window.requestAnimationFrame(anim1);
}

function anim2() {
    a2.style.left = (100 + Math.cos(t2) * 30) + 'px';
    a2.style.top = (50 + Math.sin(t2) * 30) + 'px';
    t2 += 0.055;
}
Run Code Online (Sandbox Code Playgroud)

演示:http : //jsfiddle.net/qu2Dc/2/

请注意一些差异:

  • anim1调用requestAnimationFrame以捕获下一个更新。
  • anim1获取用于计时的参数,同时anim2使用计数器。

另外,请注意,setInterval所有浏览器都支持,但requestAnimationFrame不是。例如 Internet Explorer 9 不支持它。如果您打算使用它,最好先检查它是否存在,然后将其setInterval用作后备。