Reputation: 261
I am making a game and I am trying to add a function to show the users FPS. I've been looking at some other questions on stackoverflow and other websites but they never seem to work for me. I would appreciate it if you answer. Thanks.
(Answered) - View
Upvotes: 1
Views: 1515
Reputation: 3068
Does the below solution work for you?
//
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.ieRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
let fpsElement = document.getElementById("fps");
let then = Date.now() / 1000; // get time in seconds
let render = function() {
let now = Date.now() / 1000; // get time in seconds
// compute time since last frame
let elapsedTime = now - then;
then = now;
// compute fps
let fps = 1 / elapsedTime;
fpsElement.innerText = fps.toFixed(2);
requestAnimFrame(render);
};
render();
<div>fps: <span id="fps"></span></div>
To know more about requestAnimationFrame
, refer this.
Upvotes: 2