I have 2 questions regarding the requestanimationframe polyfill function:
1)Why was element
included as an argument in window.requestAnimationFrame=function(callback, element)
?
2)Why was 16 used here: var timeToCall =Math.max(0, 16 - (currTime - lastTime));
? Is it up to the programmer judgement, not too big nor too low since we are subracting currTime-lastTime from it?
(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);
};
}());
As stated by Hacketo, element is indeed not a parameter of the window.requestAnimationFrame, it only expects the callback function.
Secondly the 16 is used to determine a maximum FPS. The setTimeout function will not fire any faster than 60 times per second. This is however a fragile approach for game synchronization. This article describes a great approach.