Skip to content

Instantly share code, notes, and snippets.

@victornpb
Created April 23, 2014 04:22
Show Gist options
  • Save victornpb/11202651 to your computer and use it in GitHub Desktop.
Save victornpb/11202651 to your computer and use it in GitHub Desktop.
FPS Meter - Returns a function that is used to compute the framerate without the overhead of updating the DOM every frame
/**
* FPS Meter - Returns a function that is used to compute the framerate without the overhead of updating the DOM every frame.
* @author Victor B - www.vitim.us
* @param {element} elm DOM Element to write the framerate
* @param {number} refresh Updates per second of the DOM
* @param {function} callback Function called on every DOM update
* @return {function} Returns a function that will be called inside the loop
*/
function fpsMeter(elm, refresh, callback){
//var elm; //element
//var refresh; //refresh every x seconds
var compRate = 1; //compute frame rate every x frames (calculated on the go)
var frames = 0; //number of frames since last timing
var last = 0; //start Timing
return function(){
if(++frames > compRate){
var now = Date.now();
var diff = now - last;
if(diff>0){
var fps = (1000/(diff/frames))<<0;
last = now;
frames = 0;
//exponential ramp the next update to match the current refresh rate
compRate = ((compRate*0.5)+((fps*refresh)*0.5))<<0;
if(elm) elm.innerHTML = fps;
if(callback) callback.call(fps);
return true;
}
else{
compRate*=2;
}
}
}
}
/* Example
var f = fpsMeter(fpsDiv, 5000);
//or
var f = fpsMeter(null, 5000, function(fps){
//console.log(fps);
fpsDiv.innerHTML = fps;
});
//game loop
setInterval(function(){
f();
//do stuff
},1);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment