JavaScript requestAnimationFrame Keeping Compatability

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Of course, just like most things in browser JavaScript, you just can't count on the fact that everything will be the same everywhere. In this case, requestAnimationFrame might have a prefix on some platforms and are named differently, such as webkitRequestAnimationFrame. Fortunately, there's a really easy way to group all the known differences that could exist down to 1 function:

window.requestAnimationFrame = (function(){
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
})();

Note that the last option (which fills in when no existing support was found) will not return an id to be used in cancelAnimationFrame. There is, however an efficient polyfill that was written which fixes this.



Got any JavaScript Question?