Skip to content

Instantly share code, notes, and snippets.

@phoboslab
Created May 6, 2012 22:04
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phoboslab/2624768 to your computer and use it in GitHub Desktop.
Save phoboslab/2624768 to your computer and use it in GitHub Desktop.
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