-
-
Save premasagar/1238789 to your computer and use it in GitHub Desktop.
Animation loop with requestAnimationFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function animLoop( render, element ){ | |
function loop( now ) { | |
requestAnimationFrame( loop, element ); | |
render( now ); | |
} | |
loop( +new Date ); | |
} | |
// Usage | |
animLoop(function( now ) { | |
// rendering code goes here | |
... | |
// optional 2nd arg: elem containing the animation | |
}, animWrapper ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function animLoop( render, element ){ | |
var lastFrame = +new Date; | |
function loop( now ) { | |
requestAnimationFrame( loop, element ); | |
render( now - lastFrame ); | |
} | |
loop( +new Date ); | |
} | |
// Usage | |
animLoop(function( deltaT ) { | |
... | |
}, animWrapper ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 always return a valid time, since: | |
// - Chrome 10 doesn't return it at all | |
// - setTimeout returns the actual timeout | |
running = render( now = ( now && now > 1E4 ? now : +new Date ), now - lastFrame ); | |
} | |
} | |
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