我试图取消一个requestAnimationFrame
循环,但我不能这样做,因为每次requestAnimationFrame
调用都会返回一个新的计时器 ID,但我只能访问第一次调用的返回值requestAnimationFrame
。
具体来说,我的代码是这样的,我认为这并不罕见:
function animate(elem) {
var step = function (timestamp) {
//Do some stuff here.
if (progressedTime < totalTime) {
return requestAnimationFrame(step); //This return value seems useless.
}
};
return requestAnimationFrame(step);
}
//Elsewhere in the code, not in the global namespace.
var timerId = animate(elem);
//A second or two later, before the animation is over.
cancelAnimationFrame(timerId); //Doesn't work!
因为所有后续调用requestAnimationFrame
都在step
函数内,所以在我想调用的事件中我无权访问返回的计时器 ID cancelAnimationFrame
。
看看Mozilla 的方式(显然还有其他人这样做),看起来他们在他们的代码中(myReq
在 Mozilla 代码中)声明了一个全局变量,然后将每次调用的返回值分配给requestAnimationFrame
该变量,以便可以使用它任何时间cancelAnimationFrame
。
有没有办法在不声明全局变量的情况下做到这一点?
谢谢你。