Skip to content

Instantly share code, notes, and snippets.

@evanre
Created April 10, 2018 17:46
Show Gist options
  • Save evanre/6d31293b5582dbbc079bf32a6bd36c20 to your computer and use it in GitHub Desktop.
Save evanre/6d31293b5582dbbc079bf32a6bd36c20 to your computer and use it in GitHub Desktop.
startAnimating(function(){
console.log('test')
}, 10);
function startAnimating(cb, fps) {
var stop = false;
var frameCount = 0;
var fps, fpsInterval, startTime, now, then, elapsed;
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animate();
function animate() {
// stop
if (stop) {
return;
}
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
now = Date.now();
elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting then=now, but...
// Also, adjust for fpsInterval not being multiple of 16.67
then = now - (elapsed % fpsInterval);
cb();
// TESTING...Report #seconds since start and achieved fps.
var sinceStart = now - startTime;
var currentFps = Math.round(1000 / (sinceStart / ++frameCount) * 100) / 100;
document.getElementById('results').innerText = "Elapsed time= " + Math.round(sinceStart / 1000 * 100) / 100 + " secs @ " + currentFps + " fps.";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment