JSFiddle - React, Tailwind, and code Playground
HTML
<p id="fps_label"># fps (# - #) [#]</p>
<button onClick="stop_test();">Stop Test</button>
<br /><br />
<strong>Tests</strong><br />
<button onClick="init_test(); run_timers();">Pure Timers</button>
<button onClick="init_test(); run_raf();">requestAnimationFrame</button>
<button onClick="init_test(); run_loop();">Interupted Loop</button>
<button onClick="init_test(); run_message(); fin();">postMessage</button>
JavaScript
/* Paul Irish's polyfill for requestAnimationFrame */
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1);
};
})();
/* Setup some global variables */
var fps_arr, fps_min, fps_max, last_time, loop_iteration;
var testing = false;
var fps_label;
/* Pretty self explanatory */
function stop_test() {
testing = false;
}
/* Resets global variables before the next test */
var init_test = function init_test() {
fps_arr = [];
fps_min = 1000;
fps_max = last_time = loop_iteration = 0;
if (typeof fps_label === 'undefined') {
fps_label = document.getElementById('fps_label');
}
testing = true;
}
var fin = function fin() {
console.log("sync");
}
/* Main loop function, updates FPS count */
function main() {
var i, fps_avg = 0;
var now = new Date().getTime();
if (last_time !== 0 && last_time !== now) {
var fps = Math.round(1000 / (now - last_time));
fps_arr.push(fps);
if (fps_arr.length > 100) {
fps_arr.shift();
}
for (i = 0; i < fps_arr.length; i++) {
fps_avg += fps_arr[i];
}
fps_avg /= fps_arr.length;
fps_avg = Math.round(fps_avg);
if (++loop_iteration > 1) {
if (fps < fps_min) {
fps_min = fps;
}
if (fps > fps_max) {
fps_max = fps;
}
}
fps_label.innerHTML = fps + ' FPS (' + fps_min + ' - ' + fps_max + ') [avg ' + fps_avg + ']';
}
last_time = now;
}
/* Pure Timers */
function run_timers() {
main();
if (testing ===...