Using requestAnimationFrame instead of timeouts
A new feature has been added quite recently to browsers in order to make animations smoother: requestAnimationFrame
. This makes the browser tell you when it's the best possible time to animate your page instead of doing it whenever you feel like it. You would use this instead of registering your callbacks with setInterval
or setTimeout
.
When you use requestAnimationFrame
, it's the browser that decides when it will call the function. Therefore, you'll have to take into account the exact time that passed since the last call. The standard specification used to define this time is milliseconds (like the ones you would get with Date.now()
), but it's now given by a high-precision timer.
As there are implementations of those two versions around, and this feature is vendor-prefixed in most browsers, you should use a tool to abstract the dirty details. I would recommend reading these two articles, both of which provide code snippets that you could use...