最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly wait for browser reflowrepaint to finish - Stack Overflow

programmeradmin0浏览0评论

Let's say I have a complex HTML component that I want to animate, but every time it needs to be animated, several things need to be done, such as rendering new HTML components, setting height, attaching css classes, etc....

This could cause the animation not being smooth if the animation gets triggered in the middle of browser reflow/repaint. I could potentially use setTmeout to delay the animation, but how long it should wait is not clear.

Is there any bullet-proof way to wait for all these browser rendering work to be done?

Let's say I have a complex HTML component that I want to animate, but every time it needs to be animated, several things need to be done, such as rendering new HTML components, setting height, attaching css classes, etc....

This could cause the animation not being smooth if the animation gets triggered in the middle of browser reflow/repaint. I could potentially use setTmeout to delay the animation, but how long it should wait is not clear.

Is there any bullet-proof way to wait for all these browser rendering work to be done?

Share Improve this question asked Apr 23, 2014 at 19:54 CookieEaterCookieEater 2,4964 gold badges35 silver badges60 bronze badges 3
  • Are you using Netscape 0.4, otherwise a reflow is so fast that you can't really time your animations to happen between reflows, and there's no way to wait for a reflow, it happens instantaneously. Maybe you were really thinking of how to wait for the window to load or something like that ? – adeneo Commented Apr 23, 2014 at 19:57
  • When adding new HTML components, keep in mind it's possible to set them up, with inner HTML and CSS, before you add them to the original DOM. Generally though, my opinion is that this won't often be as noticeable an issue as you think. – Katana314 Commented Apr 23, 2014 at 20:01
  • If your animation changes layout, a reflow is fired for each frame of the animation. – Fabrício Matté Commented Apr 23, 2014 at 20:02
Add a comment  | 

1 Answer 1

Reset to default 17

Use window.requestAnimationFrame() (https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame) - you use it in essentially the same way you would use setTimeout, but you don't specify the delay - the browser deals with it for you.

Article about it from Paul Irish here: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

Eg:

stepAnimation = function () {
  // Do something to move to the next frame of the animation
  // then
  step()
}

step = function () {
  window.requestAnimationFrame(stepAnimation)
}

step()
发布评论

评论列表(0)

  1. 暂无评论