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 ) {
var running;
function loop() {
// stop if previous render returned false
if ( running !== false ) {
requestAnimationFrame( loop, element );
running = render();
}
}
loop();
}
// Usage
animLoop(function() {
elem.style.left = ( left += 10 ) + "px";
if ( left > 400 ) {
return false;
}
// optional 2nd arg: elem containing the animation
}, animWrapper );
function animLoop( render, element ) {
var running, lastFrame = +new Date;
function loop( now ) {
// stop the loop if render returned false
if ( running !== false ) {
requestAnimationFrame( loop, element );
running = render( now - lastFrame );
lastFrame = now;
}
}
loop( lastFrame );
}
// Move the element on the right at ~600px/s
animLoop(function( deltaT ) {
elem.style.left = ( left += 10 * deltaT / 16 ) + "px";
if ( left > 400 ) {
return false;
}
});
// 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, lastFrame = +new Date;
function loop( now ) {
if ( running !== false ) {
raf ?
raf( loop, element ) :
// fallback to setTimeout
setTimeout( loop, 16 );
// Make sure to use a valid time, since:
// - Chrome 10 doesn't return it at all
// - setTimeout returns the actual timeout
now = now && now > 1E4 ? now : +new Date;
running = render( now - lastFrame, lastFrame = now );
}
}
loop();
};
})();
// Usage
animLoop(function( deltaT, 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