-
-
Save jonasfj/4438815 to your computer and use it in GitHub Desktop.
A list-based fallback implementation of `requestAnimationFrame` that reduces the number of `setTimeout`s needed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating | |
// requestAnimationFrame polyfill by Erik Möller | |
// fixes from Paul Irish and Tino Zijdel | |
// list-based fallback implementation by Jonas Finnemann Jensen | |
(function() { | |
var lastTime = 0; | |
var vendors = ['ms', 'moz', 'webkit', 'o']; | |
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { | |
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; | |
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] | |
|| window[vendors[x]+'CancelRequestAnimationFrame']; | |
} | |
if (!window.requestAnimationFrame){ | |
var tid = null, cbs = [], nb = 0, ts = 0; | |
function animate() { | |
var i, clist = cbs, len = cbs.length; | |
tid = null; | |
ts = Date.now(); | |
cbs = []; | |
nb += clist.length; | |
for (i = 0; i < len; i++){ | |
if(clist[i]) | |
clist[i](ts); | |
} | |
} | |
window.requestAnimationFrame = function(cb) { | |
if (tid == null) | |
tid = window.setTimeout(animate, Math.max(0, 20 + ts - Date.now())); | |
return cbs.push(cb) + nb; | |
}; | |
window.cancelAnimationFrame = function(id) { | |
delete cbs[id - nb - 1]; | |
}; | |
} | |
}()); |
Hey, interesting idea.
I'm not too good on scoping concepts, but would there be a problem leaving the cbs list in the global scope?
@natb19,
There is only one instance of the cbs
variable... so technically it could live in the global scope.
But I would do it because data encapsulation is a good idea :)
https://github.com/kof/animationFrame
a bit optimized version of your shim + some features and ios fix.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now a little cleaner than previous revisions, and closer to the specification.
Compared to the original approach, we don't create a new closure for each frame, but just a list and a single timeout.