requestAnimationFrame and time since last frame

by alessandro_pezzato

HTML

<span>FPS: <span id="fps"></span></span>

JavaScript

var Loop = function (step) {
    var self = this;
    var lastFrameTimestamp = null;
    var nextStep = function (timestamp) {
        if (lastFrameTimestamp === null) {
            lastFrameTimestamp = timestamp;
        }
        var tslf = timestamp - lastFrameTimestamp;
        step(tslf);
        lastFrameTimestamp = timestamp;
        self.requestID = window.requestAnimationFrame(nextStep);
    };
    
    self.stop = function() {
        window.cancelAnimationFrame(self.requestID);
    }

    nextStep();
};

var loop = new Loop(function (tslf) {
    document.getElementById('fps').innerHTML = 1000/tslf;
});

setTimeout(function() {
    loop.stop();
}, 5000);