I'm just starting HTML 5 javascript gamedevelopment, and I learned it's better to use requestAnimationFrame polyfill.

I understand the function, but I do not understand the math behind it.

to be precise:

(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);

     };

}());

the line with the math that I do not understand is:

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

Would be great if someone could give me a short explanation of how that line of code works.

Melvin Tehubijuluw

有帮助吗?

解决方案

It tries to mantain a frame ratio of 60fps. If It can't, it just puts 0 in the timeout interval ("as soon as possible*").

A frame rate of 60fps is 1/60 sec = ~0.01666.. sec = ~ 16 ms per frame.

(currTime - lastTime) is the time since the last frame was displayed, so 16 - (currTime - lastTime) is the time you should schedule the next frame if you want to mantain a 16 msec - or 60fps - delay between frames.

If the last frame took more than 16 msec to display, 16 - (currTime - lastTime) is negative (it roughly means that you should have displayed the frame 16 - (currTime - lastTime) msecs ago). In ths case, you just schedule the next frame to be displayed as soon as possible, since you can't go back in time :D

*EDIT: it should be, more precisely, "as soon as the rendering has catched up", see this question for further details.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top