Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
setAnimation; a sensible requestAnimation polyfill
// rAF polyfill based on https://gist.github.com/1579671
(function(w) {
"use strict";
// Find vendor prefix, if any
var vendors = ['ms', 'moz', 'webkit', 'o'];
for( var i = 0; i < vendors.length && !w.requestAnimationFrame; i++ ) {
w.requestAnimationFrame = w[vendors[i]+'RequestAnimationFrame'];
}
// Use requestAnimationFrame if available
if( w.requestAnimationFrame ) {
var next = 1,
anims = {};
w.setAnimation = function( callback, element ) {
var current = next++;
anims[current] = true;
var animate = function() {
if( !anims[current] ) { return; } // deleted?
w.requestAnimationFrame( animate, element );
callback();
};
w.requestAnimationFrame( animate, element );
return current;
};
w.clearAnimation = function( id ) {
delete anims[id];
};
}
// [set/clear]Interval fallback
else {
w.setAnimation = function( callback, element ) {
return w.setInterval( callback, 1000/60 );
}
w.clearAnimation = w.clearInterval;
}
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment