有没有比 setTimeout(0) 更快的方法来屈服于 Javascript 事件循环?

Is there a faster way to yield to Javascript event loop than setTimeout(0)?

我正在尝试编写一个执行可中断计算的网络工作者。据我所知,这样做的唯一方法(Worker.terminate() 除外)是定期屈服于消息循环,以便它可以检查是否有任何新消息。例如,这个 web worker 计算从 0 到 data 的整数之和,但是如果您在计算过程中向它发送一条新消息,它将取消计算并开始新的计算。

let currentTask = {
  cancelled: false,
}

onmessage = event => {
  // Cancel the current task if there is one.
  currentTask.cancelled = true;

  // Make a new task (this takes advantage of objects being references in Javascript).
  currentTask = {
    cancelled: false,
  };
  performComputation(currentTask, event.data);
}

// Wait for setTimeout(0) to complete, so that the event loop can receive any pending messages.
function yieldToMacrotasks() {
  return new Promise((resolve) => setTimeout(resolve));
}

async function performComputation(task, data) {
  let total = 0;

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    // Yield to the event loop.
    await yieldToMacrotasks();

    // Check if this task has been superceded by another one.
    if (task.cancelled) {
      return;
    }
  }

  // Return the result.
  postMessage(total);
}

这可行,但速度慢得惊人。在我的机器上,while 循环的每次迭代平均需要 4 毫秒!如果您希望快速取消,那将是一个相当大的开销。

为什么这么慢?有没有更快的方法来做到这一点?

是的,message 队列比 timeouts 队列更重要,因此触发频率更高。

您可以使用 MessageChannel API:

轻松绑定到该队列

let i = 0;
let j = 0;
const channel = new MessageChannel();
channel.port1.onmessage = messageLoop;

function messageLoop() {
  i++;
  // loop
  channel.port2.postMessage("");
}
function timeoutLoop() {
  j++;
  setTimeout( timeoutLoop );
}

messageLoop();
timeoutLoop();

// just to log
requestAnimationFrame( display );
function display() {
  log.textContent = "message: " + i + '\n' +
                    "timeout: " + j;
  requestAnimationFrame( display );
}
<pre id="log"></pre>

现在,您可能还想在每个事件循环中批处理几轮相同的操作。

以下是此方法有效的几个原因:

  • Per specssetTimeout 将在第 5 级调用后(即 OP 循环的第五次迭代后)被限制为最少 4 毫秒。
    消息事件不受此限制。

  • 在某些情况下,某些浏览器会使 setTimeout 启动的任务具有较低的优先级。
    即,Firefox does that at page loading,以便此时调用 setTimeout 的脚本不会阻止其他事件;他们甚至为此创建了一个任务队列。
    即使仍然未指定,似乎至少在 Chrome 中,消息事件有一个 "user-visible" priority,这意味着一些 UI 事件可能先出现,但仅此而已它。 (使用 Chrome 中即将到来的 scheduler.postTask() API 进行测试)

  • 大多数现代浏览器会在页面不可见时限制默认超时,而这 .
    消息事件不受此限制。

  • Chrome 确实为前 5 次调用设置了至少 1 毫秒。


但是请记住,如果所有这些限制都放在 setTimeout 上,那是因为以这样的速度安排那么多任务是有成本的。

仅在工作线程中使用!

在 Window 上下文中执行此操作会限制浏览器必须处理的所有正常任务,但他们会认为这些任务不太重要,例如网络请求、垃圾收集等。
另外,发布新任务意味着事件循环必须运行高频率并且永远不会闲置,这意味着更多的能源消耗。

Why is this so slow?

Chrome (闪烁) 实际上 sets the minimum timeout to 4 ms:

// Chromium uses a minimum timer interval of 4ms. We'd like to go
// lower; however, there are poorly coded websites out there which do
// create CPU-spinning loops.  Using 4ms prevents the CPU from
// spinning too busily and provides a balance between CPU spinning and
// the smallest possible interval timer.
static constexpr base::TimeDelta kMinimumInterval =
    base::TimeDelta::FromMilliseconds(4);

编辑:如果您进一步阅读代码,该最小值仅在嵌套级别超过 5 时使用,但在所有情况下它仍将最小值设置为 1 毫秒:

  base::TimeDelta interval_milliseconds =
      std::max(base::TimeDelta::FromMilliseconds(1), interval);
  if (interval_milliseconds < kMinimumInterval &&
      nesting_level_ >= kMaxTimerNestingLevel)
    interval_milliseconds = kMinimumInterval;

显然,WHATWG 和 W3C 规范对于最小 4 毫秒应该始终适用还是仅适用于特定嵌套级别以上存在分歧,但 WHATWG 规范才是最重要的对于 HTML,似乎 Chrome 已经实现了。

我不确定为什么我的测量表明它仍然需要 4 毫秒。


is there a faster way to do this?

基于 Kaiido 使用另一个消息通道的好主意,您可以这样做:


let currentTask = {
  cancelled: false,
}

onmessage = event => {
  currentTask.cancelled = true;
  currentTask = {
    cancelled: false,
  };
  performComputation(currentTask, event.data);
}

async function performComputation(task, data) {
  let total = 0;

  let promiseResolver;

  const channel = new MessageChannel();
  channel.port2.onmessage = event => {
    promiseResolver();
  };

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    // Yield to the event loop.
    const promise = new Promise(resolve => {
      promiseResolver = resolve;
    });
    channel.port1.postMessage(null);
    await promise;

    // Check if this task has been superceded by another one.
    if (task.cancelled) {
      return;
    }
  }

  // Return the result.
  postMessage(total);
}

我对这段代码不是很满意,但它似乎确实有效,而且 waaay 更快。在我的机器上每个循环大约需要 0.04 毫秒。

我可以确认 setTimeout(..., 0) 的 4 毫秒往返时间,但并不一致。我使用了以下工作人员(以 [=12= 开始,以 w.terminate() 结束)。

在前两轮中,停顿小于 1 毫秒,然后我得到一个在 8 毫秒范围内的停顿,然后每次迭代都保持在 4 毫秒左右。

为了减少等待,我将 yieldPromise 执行程序移到了工作负载前面。这样 setTimeout() 可以保持最小延迟,而不会暂停工作循环超过必要的时间。我想工作负载必须长于 4ms 才能有效。这应该不是问题,除非捕获取消消息是工作量......;-)

结果:仅延迟约 0.4 毫秒。 即减少至少 10 倍。1

'use strict';
const timer = performance.now.bind(performance);

async function work() {
    while (true) {
        const yieldPromise = new Promise(resolve => setTimeout(resolve, 0));
        const start = timer();
        while (timer() - start < 500) {
            // work here
        }
        const end = timer();
        // const yieldPromise = new Promise(resolve => setTimeout(resolve, 0));
        await yieldPromise;
        console.log('Took this time to come back working:', timer() - end);
    }
}
work();


1浏览器不是把定时器分辨率限制在那个范围内吗?没有办法衡量进一步的改进......

查看 , I tried to challenge the code in 中的否决票,我的新知识是 setTimeout(..., 0) 有大约 4 毫秒的强制延迟(至少在 Chromium 上)。我在每个循环中放置了 100 毫秒的工作负载,并在工作负载之前安排了 setTimeout(),这样 setTimeout() 的 4 毫秒就已经过去了。为了公平起见,我对 postMessage() 做了同样的事情。我还更改了日志记录。

结果令人惊讶:在观察计数器时,消息方法在开始时比超时方法获得了 0-1 次迭代,但它保持不变 甚至高达 3000 次迭代。 – 这证明 setTimeout() 和并发 postMessage() 可以保持其份额(在 Chromium 中)。

将 iframe 滚动到范围之外改变了结果:与基于超时的工作负载相比,处理的消息触发的工作负载几乎是 10 倍。这可能与浏览器打算将更少的资源交给视图之外或在另一个选项卡中的 JS 等有关。

在 Firefox 上,我看到工作负载处理带有 7:1 超时消息。观看或将其留在另一个选项卡上 运行 似乎并不重要。

现在我将(稍微修改过的)代码移到了 Worker 中。 结果表明,通过 timeout-scheduling 处理的迭代是 完全与基于消息的调度相同。在 Firefox 和 Chromium 上我得到相同的结果。

let i = 0;
let j = 0;
const channel = new MessageChannel();
channel.port1.onmessage = messageLoop;

timer = performance.now.bind(performance);

function workload() {
  const start = timer();
  while (timer() - start < 100);
}

function messageLoop() {
  i++;
  channel.port2.postMessage("");
  workload();
}
function timeoutLoop() {
  j++;
  setTimeout( timeoutLoop );
  workload();
}

setInterval(() => log.textContent =
  `message: ${i}\ntimeout: ${j}`, 300);

timeoutLoop();
messageLoop();
<pre id="log"></pre>