我在这里阅读了一篇关于 requestAnimationFrame 的文章,我意识到我在跟踪变量的范围和持久性时遇到了问题。稍作修改的代码如下:
(function() {
//Note: lastTime is defined up here.
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
//Okay, so they're trying to set window.rAF to the appropriate thing based on browser
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
//...and if that doesn't work, turn it into a setTimeout
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
//I guess this is a way to make sure that the wait time
//between renders is consistent
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;
//Wait. They just assigned lastTime a value.
//Why is this going to persist between calls to window.rAF?
//The variable lastTime was defined inside this function, not in the window.
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())
我的猜测是它与放在括号内的函数有关,但是如何?使用这种编码风格可以完成什么以及我可以期待什么其他效果?这是我应该开始更经常使用的东西吗?如果是,什么时候?