为什么requestAnimationFrame的许多示例在回调之外调用requestAnimationFrame?

问题描述 投票:-1回答:1

我在网上看到的RequestAnimationFrame的很多例子都调用了两次函数:回调内部和外部。我理解为什么我们在里面称呼它;但是,我们称之为外面的任何理由?

Reference

let myReq;

function step(timestamp) {
  myReq = requestAnimationFrame(step); // I understand why we call it here.
  console.log(timestamp, myReq)
  if(timestamp >= 1000) {
    cancelAnimationFrame(myReq);
  }
}

myReq = requestAnimationFrame(step);  // why invoke rAF here.
javascript requestanimationframe
1个回答
2
投票

这是step的初始调用,在下一个动画帧;它基本上是开始动画。没有它,你有这个:

let myReq;

function step(timestamp) {
  myReq = requestAnimationFrame(step);
  console.log(timestamp, myReq)
  if(timestamp >= 1000) {
    cancelAnimationFrame(myReq);
  }
}

...在这种情况下,我们从来没有调用step,它永远不会被调用。

或者你可以省略requestAnimationFrame包装器到step的初始调用:

let myReq;

function step(timestamp) {
  myReq = requestAnimationFrame(step); // I understand why we call it here.
  console.log(timestamp, myReq)
  if(timestamp >= 1000) {
    cancelAnimationFrame(myReq);
  }
}

myReq = step;  // why invoke rAF here.

但是,当第一次调用step时,它不一定会等待第一个可用的动画帧。

© www.soinside.com 2019 - 2024. All rights reserved.