标签: cancelanimationframe

有没有办法在没有全局变量的情况下取消 requestAnimationFrame ?

我试图取消一个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 代码中),然后将每次调用的返回值分配给 …

javascript global-variables requestanimationframe cancelanimationframe

1
推荐指数
1
解决办法
1540
查看次数