Requestanimationframework polyfill

Hi All, I have read from web about requestanimationframe polyfill but one line i didn’t understand.

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
 
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
 
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

here i didn’t undertstand why
lastTime = currTime + timeToCall;

comes after

var timeToCall = Math.max(0, 16 - (currTime - lastTime));

whereas timeToCall uses lastTime variable?
Thanks for attention

The lastTime variable is initialized at the top of the main function. The function passed to requestAnimationFrame retains access to that lastTime variable via a technique called closure, which allows it to access and update the variable.

oo i now saw it , Thanks very much

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.