Skip to content

Instantly share code, notes, and snippets.

@premasagar
Forked from louisremi/animLoopX.js
Created September 24, 2011 00:47
Show Gist options
  • Save premasagar/1238789 to your computer and use it in GitHub Desktop.
Save premasagar/1238789 to your computer and use it in GitHub Desktop.
Animation loop with requestAnimationFrame
function animLoop( render, element ){
function loop( now ) {
requestAnimationFrame( loop, element );
render( now || +new Date );
}
loop();
}
// Usage
animLoop(function() {
// rendering code goes here
...
// optional 2nd arg: elem containing the animation
}, animWrapper );
// Cross browser, backward compatible solution
(function() {
// feature testing
var raf = window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
window.animLoop = function( render, element ) {
var running;
function loop( now ) {
if ( running !== false ) {
raf ?
raf( loop, element ) :
// fallback to setTimeout
setTimeout( loop, 16 );
// Make sure to always return a valid time, since:
// - Chrome 10 doesn't return it at all
// - setTimeout returns the actual timeout
running = render( now && now > 1E4 ? now : +new Date );
}
}
loop();
};
})();
// Usage
animLoop(function( now ) {
// rendering code goes here
// return false; will stop the loop
...
// optional 2nd arg: elem containing the animation
}, animWrapper );
// minified to 208B, to see if it was tweetable, but :-(
(function(b,a){a="RequestAnimationFrame";a=b["moz"+a]||b["webkit"+a]||b["ms"+a]||b["o"+a];b.animLoop=function(b,f,e){function c(d){e!==!1&&(a?a(c,f):setTimeout(c,16),e=b(d&&d>1E4?d:+new Date))}c()}})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment