Menu

Using setTimeout and requestAnimationFrame in the CSS + JS animation

More recently, to build CSS + JS animation was enough to use setTimeout. Today - this decision is no longer relevant (problem especially occurs in Chrome).

Progress runs and take everything, including browsers. And last, in turn, "sacrificed" setTimeout towards performance. I think this was not done on purpose. :)

The idea is that when you change styles for elements, their use occurs only in moments of redrawing. That is, suppose there anim class, where a number of styles "transition: all 5s linear;" and this class hangs in the DIV. And then we wanted, this magic the DIV, quickly move to a new position.

How some (but what is really there, and I have sinned :)) done this before.

el.classList.remove("anim");

el.style.left = "200px";

setTimeout(function() {

  el.classList.add("anim");

}, 0);

From the point of view of logic - such as normal. Stole class, changed position, through the "moment" - returned to class. Element sort to jump to a new position. And sometimes it is even impossible. 

But in fact, occasionally it can be seen as an element moves smoothly to the new position.

Here are two solutions:

use requestAnimationFrame Instead of setTimeout;

- remove element form DOM tree, then change position, and adding to the tree again.

What would be closer to touch an example, I offer to visit jsfiddle examples.

Here, incorrect version with setTimeout:

https://jsfiddle.net/ByTiger/d5fjmbwg/

And here, a faithful version with requestAnimationFrame:

https://jsfiddle.net/ByTiger/tzz4L219/2/

P.s.: Statement of the problem technically competent report does not pull, but I think the problem is clear. :)

Tags:
js, javascript, css, animation, transition, setTimeout, requestAnimationFrame

Keep your comment...