<
h1
>Controlling requestAnimationFrame to a FPS</
h1
>
<
h2
>This test: Results should be approximately 5 fps</
h2
>
<
h2
id
=
"results"
>Results:</
h2
>
<
canvas
id
=
"canvas"
width
=
"300"
height
=
"300"
></
canvas
>
<
script
>
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;
startAnimating(5);
function startAnimating(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
console.log(startTime);
animate();
}
function animate() {
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since the last loop
now = Date.now();
elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
// draw animating objects here...
// below code is used for testing, whether
// the frame is animating at the specified fps
var sinceStart = now - startTime;
var currentFps =
Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100;
$results.text("Elapsed time= "
+ Math.round((sinceStart / 1000) * 100) / 100
+ " secs @ " + currentFps + " fps.");
}
}
</
script
>