Sign in to follow this  
Gustavgb

How to calculate FPS in plain Javascript?

Recommended Posts

Hello everyone,

Lately I have been making a bunch of small web games. Therefore I'm quite interrested in: How to calculate the FPS of the game.

I make my games in plain Javascript, and therefore I would like to know how to calculate the FPS in plain Javascript.

 

I hope that was enough explanation.

 

Thanks! :)

Share this post


Link to post
Share on other sites

Hey, I use this little snippet to get the current fps of my games.

var fps = {	startTime : 0,	frameNumber : 0,	getFPS : function(){		this.frameNumber++;		var d = new Date().getTime(),			currentTime = ( d - this.startTime ) / 1000,			result = Math.floor( ( this.frameNumber / currentTime ) );		if( currentTime > 1 ){			this.startTime = new Date().getTime();			this.frameNumber = 0;		}		return result;	}	};

You should call fps.getFPS() on your game loop.

 

For example : 

var f = document.querySelector("#fps");function gameLoop(){	setTimeout( gameLoop,1000 / 60 );	f.innerHTML = fps.getFPS();}window.onload = gameLoop;

Share this post


Link to post
Share on other sites

Assuming you're using requestAnimationFrame, you can do this:

function Timer () {  this.elapsed = 0  this.last = null}Timer.prototype = {  tick: function (now) {    this.elapsed = (now - (this.last || now) / 1000    this.last = now  },  fps: function () {    return Math.round(1 / this.elapsed)  }}var timer = new Timer()function render (now) {  requestAnimationFrame(render)  timer.tick(now)  // Get the current FPS with a call to timer.fps()}requestAnimationFrame(render)
Edited by onefrankguy

Share this post


Link to post
Share on other sites

 

Assuming you're using requestAnimationFrame, you can do this:

function Timer () {  this.elapsed = 0  this.last = null}Timer.prototype = {  tick: function (now) {    this.elapsed = (now - (this.last || now) / 1000    this.last = now  },  fps: function () {    return Math.round(1 / this.elapsed)  }}var timer = new Timer()function render (now) {  requestAnimationFrame(render)  timer.tick(now)  // Get the current FPS with a call to timer.fps()}requestAnimationFrame(render)

This calculates the average framerate, right?

 

I think instant framerate is more relevant. I usually calculate the framerate based on the last 60 frames only. This way you have enough time to read it, and it represents the current performance of your game.

 

This is my code:

    cycle : function(){        var now = Date.now();        var elapsed = Math.min((now - this.lastCycle) / 1000,1/this.fpsMin);        this.lastCycle = now;                // Triggering cycle only if not paused and with focus        if(!this.pause){            try{                this.oncycle(elapsed);            }catch(e){                console.log('Error: ' + e + ' - ');                throw e;            }                        // Calculating FPS            this.framesUntilNextStat--;            if(this.framesUntilNextStat <= 0){                this.framesUntilNextStat = 60; // Scheduling the next statistics                this.fps = ~~(60 * 1000 / (Date.now() - this.lastStat + elapsed));                this.lastStat = Date.now();            }        }    }

Dirty and old, but it works ;)

Share this post


Link to post
Share on other sites

This calculates the average framerate, right?

 

It's actually the current frame rate. The Timer.tick function gets called before the browser repaints, so Timer.elapsed is actually tracking the seconds between the last repaint and the repaint that's going to happen next. It's basically "seconds per frame", which I invert to get frames per second. I only redraw my FPS counter every second, since as you mentioned, if you redraw it faster than that it's not readable.

var timer = new Timer()  , then = 0function render (now) {  requestAnimationFrame(render)  timer.tick(now)  if (now - then > 1000) {    then = now    $('#fps').innerHTML = timer.fps()  }}

I like your idea of doing an average over the last sixty frames. I'm going to have to play around with that.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.