使用requestAnimationFrame创建无限事件循环是否有性能成本?

Is there a performance cost to create an infinite event loop using requestAnimationFrame

本文关键字:性能 是否 循环 requestAnimationFrame 创建 无限 事件 使用      更新时间:2023-09-26

如果我需要一个事件循环在javascript永远运行(也许查询循环内的REST api),是否有任何性能损失,如果它实现如下

function eventLoop() {
// Call to REST api
requestAnimationFrame(eventLoop);
}
requestAnimationFrame(eventLoop);

或如下所示

http://codepen.io/chriscoyier/pen/ltseg

requestAnimationFrame,顾名思义,是用来渲染动画的。它具有高达60 fps左右的高迭代率。如果您正在轮询API(可能会花费大量时间来返回响应),这听起来有点过分。

为什么不直接使用setTimeout ?您可以轮询API,然后当请求返回时,可选地再次轮询。

var timer;
function pollAPI() {
    $.ajax({
      success: function(response) {
        if (response == 'something') {
            // do something
        } else {
            // poll again
            timer = setTimeout(pollAPI, 50);
        }
      }
    });
}
pollAPI();

这很好,但是如果你在互联网上做一些异步的事情,比如ajax调用,你应该在重新启动之前等待适当的时间,否则你最终会每秒向自己发送60个请求。