0

我试图取消一个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

有没有办法在不声明全局变量的情况下做到这一点?
谢谢你。

4

1 回答 1

5

它不需要是全局变量;它只需要具有范围以便两者都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.

编辑:您不需要每次都对其进行编码——这就是为什么我们要做编程,毕竟,要抽象重复的东西,所以我们不需要自己做。:)

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
});
于 2015-07-08T02:10:44.960 回答