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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment