简体   繁体   English

在 requestIdleCallback 中使用 requestAnimationFrame

[英]Using requestAnimationFrame inside requestIdleCallback

If I animate changes in the DOM from JS (eg changing the value of a node's textContent from 1 to 500), would it be better to use requestAnimationFrame or requestAnimationFrame within a requestIdleCallback ?如果我从 JS 对 DOM 中的更改进行动画处理(例如,将节点的 textContent 的值从 1 更改为 500),在requestIdleCallback中使用requestAnimationFramerequestAnimationFrame会更好吗?

If you want to animate some code, then use only requestAnimationFrame , if you want to perform an action only when the browser has nothing else to do anymore, then use requestIdleCallback .如果您想为某些代码设置动画,则仅使用requestAnimationFrame ,如果您只想在浏览器无事可做时执行操作,则使用requestIdleCallback

To simplify things, let's consider that both requestAnimationFrame and requestIdleCallback are setTimeout calls, with variables timeout arguments.为简化起见,让我们考虑requestAnimationFramerequestIdleCallback都是setTimeout调用,变量 timeout arguments。

requestAnimationFrame would then be setTimeout(fn, time_until_next_screen_refresh) . requestAnimationFrame然后将是setTimeout(fn, time_until_next_screen_refresh) fn will be called right before the page is painted to the screen. fn将在页面绘制到屏幕之前被调用。 This is currently the best timer we have to make animations since it ensures we'll only do the visual modifications only once per actual frame, at the speed of what the monitor is able to render, thus at every frame, if our code is fast enough.这是目前我们必须制作动画的最佳计时器,因为它确保我们在每个实际帧中只进行一次视觉修改,以监视器能够渲染的速度,因此在每一帧,如果我们的代码很快足够的。

requestIdleCallback would be setTimeout(fn, time_until_idle) . requestIdleCallback将是setTimeout(fn, time_until_idle) fn will be called as soon as the browser has nothing more to do.一旦浏览器无事可做, fn就会被调用。 This can be right away, or in a few event loops iterations.这可以立即进行,也可以在几个事件循环迭代中进行。

So while both have a similar API, they provide completely different features, and the only viable one for doing an animation is requestAnimationFrame , since requestIdleCallback has basically no link whatsoever with the rendering.因此,虽然两者都有类似的 API,但它们提供了完全不同的功能,唯一可行的 animation 是requestAnimationFrame ,因为requestIdleCallback基本上与渲染没有任何联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM