How to properly wait for browser reflow/repaint to finish
css, html, javascript
Solution
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()
Problem
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?