Har*_*San 1 javascript global-variables requestanimationframe cancelanimationframe
我试图取消一个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!
Run Code Online (Sandbox Code Playgroud)
因为所有后续调用都requestAnimationFrame在该函数内step,所以在我想要调用的事件中,我无权访问返回的计时器 ID cancelAnimationFrame。
看看Mozilla(显然还有其他人这样做)的方式,看起来他们在代码中声明了一个全局变量(myReq在 Mozilla 代码中),然后将每次调用的返回值分配给requestAnimationFrame该变量,以便可以使用它任何时间cancelAnimationFrame。
有没有办法在不声明全局变量的情况下做到这一点?
谢谢。
它不需要是全局变量;它只需要有一个范围,使得 和animate都cancel可以访问它。即你可以封装它。例如,这样的事情:
var Animation = function(elem) {
var timerID;
var step = function() {
// ...
timerID = requestAnimationFrame(step);
};
return {
start: function() {
timerID = requestAnimationFrame(step);
}
cancel: function() {
cancelAnimationFrame(timerID);
}
};
})();
var animation = new Animation(elem);
animation.start();
animation.cancel();
timerID; // error, not global.
Run Code Online (Sandbox Code Playgroud)
编辑:你不需要每次都编码- 这就是我们进行编程的原因,毕竟,是为了抽象重复的东西,这样我们就不需要自己做。:)
var Animation = function(step) {
var timerID;
var innerStep = function(timestamp) {
step(timestamp);
timerID = requestAnimationFrame(innerStep);
};
return {
start: function() {
timerID = requestAnimationFrame(innerStep);
}
cancel: function() {
cancelAnimationFrame(timerID);
}
};
})();
var animation1 = new Animation(function(timestamp) {
// do something with elem1
});
var animation2 = new Animation(function(timestamp) {
// do something with elem2
});
Run Code Online (Sandbox Code Playgroud)