<h3>Throttling requestAnimationFrame to a FPS</h3>
<p>This test: Results should be approximately 5 fps
<p id="results">Results:</p>
<canvas id="canvas" width=300 height=300></canvas>
JavaScript
var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;
startAnimating(5);
function startAnimating(fps) {
fpsInterval = 1000 / fps;
then = window.performance.now();
startTime = then;
console.log(startTime);
animate();
}
function animate(newtime) {
// stop
if (stop) {
return;
}
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
now = newtime;
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);
// draw stuff here
// TESTING...Report #seconds since start and achieved 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.");
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.