gpt4 book ai didi

javascript - requestAnimationFrame 处理顺序

转载 作者:行者123 更新时间:2023-11-30 16:19:56 32 4
gpt4 key购买 nike

如果我有以下代码:

window.requestAnimationFrame(animation1); //animation1 takes more than 16.67ms, misses the frame.
window.requestAnimationFrame(animation2); //animation2 takes 1ms to execute

假设 animation1animation2 是简单的颜色变化动画,是否意味着 animation2 会在 animation1< 之前出现在屏幕上?

或者对 requestAnimationFrame 的调用是否堆叠在浏览器队列中,后续调用只会在前一个调用完成时执行?

最佳答案

长话短说

animation1 将始终在调用 animation2 之前运行完成,但如果它们中的任何一个花费的时间太长,浏览器可能不会调用它们中的任何一个以获取帧或两个。


The specification对于 requestAnimationFrame 说:

When the requestAnimationFrame() method is called, the user agent must run the following steps: ...

  1. Append the method's argument to document's list of animation frame callbacks, associated with document's animation frame callback identifier's current value.

和:

When the user agent is to run the animation frame callbacks for a Document doc with a timestamp now, it must run the following steps:

  1. Let callbacks be a list of the entries in doc's list of animation frame callbacks, in the order in which they were added to the list.

所以我们可以通过运行看到:

window.requestAnimationFrame(animation1);
window.requestAnimationFrame(animation2);

您正在排队 animation1animation2 以在下次 “用户代理运行动画帧回调” 时调用。

那个时候is specified作为主事件循环的一部分:

  1. For each fully active Document in docs, run the animation frame callbacks for that Document, passing in now as the timestamp.

然而在此之前,它指定:

  1. If there is a top-level browsing context B that the user agent believes would not benefit from having its rendering updated at this time, then remove from docs all Document objects whose browsing context's top-level browsing context is B.

这意味着如果您的回调花费的时间太长,它可能会决定丢帧而不运行它们。但是,由于所有请求的帧都在第 9 步中一个接一个地执行,您应该总是animation2 之前看到 animation1 的结果,但是浏览器可能决定从它的渲染循环中删除整个文档,并且在事件循环的后续迭代之前不调用队列中的任一个方法。

关于javascript - requestAnimationFrame 处理顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34904470/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com