Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurate Timing with RequestAnimationFrame

I've not found a lot of documentation on this subject so far. The general feel I get is when implementing animations for the browser it is better to use RequestAnimationFrame over bog standard JavaScript timers. My understanding is that timers are unreliable and their resolution can vary between different browsers.

I've been looking at this gist: https://gist.github.com/1114293#file_anim_loop_x.js

But it's not clear to me how you can ensure that an animation transpires over a fixed amount of time. For example I might want to animate something from left to right within 2 seconds. Is this do-able using RequestAnimationFrame or does it defeat the purpose?

like image 587
backdesk Avatar asked Mar 15 '12 08:03

backdesk


1 Answers

It just so happens, I had a similar problem not long ago and came up with an approach which combines rAF with performance.now() which works very effectively.

Im now able to make timers accurate to approx 12 decimal places:

    window.performance = window.performance || {};
    window.performance.now = (function() {
        return performance.now       ||
            window.performance.mozNow    ||
            window.performance.msNow     ||
            window.performance.oNow      ||
            window.performance.webkitNow ||
                function() {
                    return new Date().getTime(); 
                };
        })();

http://jsfiddle.net/CGWGreen/9pg9L/

like image 75
Chris GW Green Avatar answered Sep 21 '22 05:09

Chris GW Green