为什么建议在重绘后安排某些内容时将 setTimeout 嵌套在 requestAnimationFrame 中?

Why is it recommend to nest setTimeout in requestAnimationFrame when scheduling something after a repaint?

mozilla docs on performance best practices for front-end engineers 中,建议在重绘后立即将 setTimeoutrequestAnimationFrame 结合到 运行 中:

requestAnimationFrame(() => {
  setTimeout(() => {
    // This code will be run ASAP after Style and Layout information have
    // been calculated and the paint has occurred. Unless something else
    // has dirtied the DOM very early, querying for style and layout information
    // here should be cheap.
  }, 0);
});

为什么这是推荐的解决方案?究竟是什么使它成为重绘后立即安排某些事情的最佳方式?

Why is this the recommended solution? What exactly makes this the optimal way to schedule something right after a repaint?

运行 代码在重绘之后立即最大化 DOM 已被完全计算的机会,从而最小化查询 dom 将导致代价高昂的回流的机会。如果您不查询 dom,那么这不是您需要担心的事情。

requestAnimationFrame 将在 重绘 之前立即将代码安排到 运行,这接近您想要的位置,但不完全是。因此,然后执行 0 的 setTimeout(或 setImmediate 在支持它的浏览器上)将在此之后尽快执行代码。这不能保证您的代码是重绘后 运行 的第一件事,但这是您可以使用的最好的 api。