Ruslan Aliyev
Ruslan Aliyev

Reputation: 29

JS requestAnimationFrame frame-rate

JavaScript, requestAnimationFrame:

You know how the frame-rate is different in different situations (i.e. different browsers for eg)

How do I find out the frame-rate in a particular case?

Thank you

Upvotes: 1

Views: 347

Answers (1)

Michael Tyken Frank
Michael Tyken Frank

Reputation: 21

Here's a function to find frame rate that relies on requestAnimationFrame() for any device that supports it. Only drawback is that precision is not instantaneous. You could easily round to the nearest standard framerate and get a very quick return value that way, but this code calculates an average over 60 frames to get a more accurate reading of requestAnimationFrame().

function RAF_tester() {
    var i = 1;
    var prevT;
    requestAnimationFrame(function(startT) {
        requestAnimationFrame(function RAF_loop(currentT) {
            var elapsedT = currentT - startT;
            var RAF_interval = currentT - prevT;
            var RAF_average = 1000 / (elapsedT / i);
            console.log(RAF_interval);
            diagnostic.innerHTML = 'Average FPS: '+RAF_average;
            prevT = currentT;
            i += 1; if (i<61) { requestAnimationFrame(RAF_loop); }
        });
    });
}

Hopefully it works for you!

Try it on codepen: http://codepen.io/kandleflame/pen/QEgQoE

Upvotes: 2

Related Questions