This method is strong and reliable, utilizing the requestAnimationFrame feature.
function calculateFramesPerSecond(options){
var requestFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
if (!requestFrame) return true; // Determine if "true" is returned;
// set default FPS, display error message, etc...
function checkFramerate(){
if (index--) requestFrame(checkFramerate);
else {
// var result = 3*Math.round(count*1000/3/(performance.now()-start));
var result = count*1000/(performance.now()- start);
if (typeof options.callback === "function") options.callback(result);
console.log("Calculated: "+result+" frames per second");
}
}
if (!options) options = {};
var count = options.count||60, index = count, start = performance.now();
checkFramerate();
}
The higher the count
, the more precise the FPS value will be, but it will also increase test duration.
You can implement additional logic for rounding to intervals like 15/12s, such as 24, 30, 48, 60, 120... FPS.
Here's the condensed version (rounded to 3 FPS):
function calcFPS(a){function b(){if(f--)c(b);else{var e=3*Math.round(1E3*d/3/(performance.now()-g));"function"===typeof a.callback&&a.callback(e);console.log("Calculated: "+e+" frames per second")}}var c=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;if(!c)return!0;a||(a={});var d=a.count||60,f=d,g=performance.now();b()}
Usage examples:
calcFPS(); // Simply logs output to the console (console log can be removed,
// rendering this call unnecessary)
calcFPS({count: 30}); // Manually define the count (test duration should be around 500ms
// on a 60FPS display)
calcFPS({callback: useFPS}); // Specify a callback function to utilize
// the FPS value
var FPS = 0, err = calcFPS({count: 120, callback: fps => FPS = fps});
if (err) FPS = 30;