Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly wait for browser reflow/repaint to finish

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?

like image 337
CookieEater Avatar asked Dec 25 '22 10:12

CookieEater


1 Answers

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()
like image 125
Trolleymusic Avatar answered Dec 28 '22 05:12

Trolleymusic