Calculate FPS in Canvas using requestAnimationFrame

How could I calculate the FPS of a canvas game application? I've seen some examples, but none of them use requestAnimationFrame, and im not sure how to apply their solutions there. This is my code:

(function(window, document, undefined){

    var canvas       = document.getElementById("mycanvas"),
        context      = canvas.getContext("2d"),
        width        = canvas.width,
        height       = canvas.height,
        fps          = 0,
        game_running = true,
        show_fps     = true;

    function showFPS(){
        context.fillStyle = "Black";
        context.font      = "normal 16pt Arial";

        context.fillText(fps + " fps", 10, 26);
    function gameLoop(){

        //Clear screen
        context.clearRect(0, 0, width, height);

        if (show_fps) showFPS();

        if (game_running) requestAnimationFrame(gameLoop);


}(this, this.document))
    border: 3px solid #fd3300;
<canvas id="mycanvas" width="300" height="150"></canvas>

By the way, is there any library I could add to surpervise performance?



Do not use new Date()

This API has several flaws and is only useful for getting the current date + time. Not for measuring timespans.

The Date-API uses the operating system's internal clock, which is constantly updated and synchronized with NTP time servers. This means, that the speed / frequency of this clock is sometimes faster and sometimes slower than the actual time - and therefore not useable for measuring durations and framerates.

If someone changes the system time (either manually or due to DST), you could at least see the problem if a single frame suddenly needed an hour. Or a negative time. But if the system clock ticks 20% faster to synchronize with world-time, it is practically impossible to detect.

Also, the Date-API is very imprecise - often much less than 1ms. This makes it especially useless for framerate measurements, where one 60Hz frame needs ~17ms.

Instead, use

The Performance API has been specificly made for such use cases and can be used equivalently to new Date(). Just take one of the other answers and replace new Date() with, and you are ready to go.


Also unlike, the values returned by always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + will be approximately equal to

And for windows:

[The time service] adjusts the local clock rate to allow it to converge toward the correct time. If the time difference between the local clock and the [accurate time sample] is too large to correct by adjusting the local clock rate, the time service sets the local clock to the correct time.


You could keep track of the last time requestAnimFrame was called.

var lastCalledTime;
var fps;

function requestAnimFrame() {

  if(!lastCalledTime) {
     lastCalledTime =;
     fps = 0;
  delta = ( - lastCalledTime)/1000;
  lastCalledTime =;
  fps = 1/delta;


Chrome has a built-in fps counter:

enter image description here

Just open the dev-console (F12), open the drawer (Esc), and add the "Rendering" tab.

Here, you can activate the FPS-Meter overlay to see the current framerate (incl. a nice graph), as well as GPU memory consumption.

Cross-browser solution: You can get a similar overlay with the JavaScript library stat.js:

enter image description here

It also provides a nice overlay for the framerate (incl. graph) and is very easy to use.

When comparing the results from stats.js and the chrome dev tools, both show the exact same measurements. So you can trust that library to actually do the correct thing.


I have a different approach, because if you calculate the the FPS you'll get this flickering when returning the number. I decided to count every Frame and return it once a second

window.countFPS = (function () {
  var lastLoop = (new Date()).getMilliseconds();
  var count = 1;
  var fps = 0;

  return function () {
    var currentLoop = (new Date()).getMilliseconds();
    if (lastLoop > currentLoop) {
      fps = count;
      count = 1;
    } else {
      count += 1;
    lastLoop = currentLoop;
    return fps;

requestAnimationFrame(function () {



Here's another solution:

var times = [];
var fps;

function refreshLoop() {
  window.requestAnimationFrame(function() {
    const now =;
    while (times.length > 0 && times[0] <= now - 1000) {
    fps = times.length;


This improves on some of the others in the following ways:

  • is used over for increased precision (as covered in this answer)
  • FPS is measured over the last second so the number won't jump around so erratically, particularly for applications that have single long frames.

I wrote about this solution in more detail on my website.


Just check the difference in time between the AFR-callbacks. AFR already passes the time as an argument to the callback. I updated your fiddle to show it:


Just a proof of concept. Very simple code. All we do is set our frames per second and intervals between each frame. In the drawing function we deduct our last frame’s execution time from the current time to check whether the time elapsed since the last frame is more than our interval (which is based on the fps) or not. If the condition evaluates to true, we set the time for our current frame which is going to be the “last frame execution time” in the next drawing call.

var GameLoop = function(fn, fps){
    var now;
    var delta;
    var interval;
    var then = new Date().getTime();

    var frames;
    var oldtime = 0;

    return (function loop(time){

        interval = 1000 / (this.fps || fps || 60);
        now = new Date().getTime();
        delta = now - then;

        if (delta > interval) {
            // update time stuffs
            then = now - (delta % interval);

            // calculate the frames per second
            frames = 1000 / (time - oldtime)
            oldtime = time;

            // call the fn
            // and pass current fps to it


var set;
document.onclick = function(){
    set = true;

    if(set) this.fps = 30;
}, 5);


Actually none of the answers were sufficient for me. Here is a better solution which:

  • Use's
  • Calculates the actual average fps per second
  • Average per second and decimal places are configurable


// Options
const outputEl         = document.getElementById('fps-output');
const decimalPlaces    = 2;
const updateEachSecond = 1;

// Cache values
const decimalPlacesRatio = Math.pow(10, decimalPlaces);
let timeMeasurements     = [];

// Final output
let fps = 0;

const tick = function() {

  const msPassed = timeMeasurements[timeMeasurements.length - 1] - timeMeasurements[0];

  if (msPassed >= updateEachSecond * 1000) {
    fps = Math.round(timeMeasurements.length / msPassed * 1000 * decimalPlacesRatio) / decimalPlacesRatio;
    timeMeasurements = [];

  outputEl.innerText = fps;

  requestAnimationFrame(() => {




I was missing an implementation that allows to customize the size of the sample for the averaged FPS value. Here is mine , it has the following features :

  • Accurate : based
  • Stabilized : Returned FPS value is an averaged value ( fps.value | fps.tick() )
  • Configurable : FPS samples array size can be customized ( fps.samplesSize )
  • Efficient : Rotatory array for collecting samples (avoids array resizing)

const fps = {
    sampleSize : 60,    
    value : 0,
    _sample_ : [],
    _index_ : 0,
    _lastTick_: false,
    tick : function(){
        // if is first tick, just set tick timestamp and return
        if( !this._lastTick_ ){
            this._lastTick_ =;
            return 0;
        // calculate necessary values to obtain current tick FPS
        let now =;
        let delta = (now - this._lastTick_)/1000;
        let fps = 1/delta;
        // add to fps samples, current tick fps value 
        this._sample_[ this._index_ ] = Math.round(fps);
        // iterate samples to obtain the average
        let average = 0;
        for(i=0; i<this._sample_.length; i++) average += this._sample_[ i ];

        average = Math.round( average / this._sample_.length);

        // set new FPS
        this.value = average;
        // store current timestamp
        this._lastTick_ = now;
        // increase sample index counter, and reset it
        // to 0 if exceded maximum sampleSize limit
        if( this._index_ === this.sampleSize) this._index_ = 0;
        return this.value;

// *******************
// test time...
// *******************

function loop(){
    let fpsValue = fps.tick();
    window.fps.innerHTML = fpsValue;
    requestAnimationFrame( loop );
// set FPS calulation based in the last 120 loop cicles 
fps.sampleSize = 120;
// start loop
<div id="fps">--</div>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.