window.requestAnimationFrame()如何工作?

时间:2018-05-08 20:10:11

标签: javascript

我如何理解以下代码?我是JavaScript的新手。

var start = null;
var element = document.getElementById('SomeElementYouWantToAnimate');
element.style.position = 'absolute';

function step(timestamp) {
   if (!start) start = timestamp;
      var progress = timestamp - start;
      element.style.left = Math.min(progress / 10, 200) + 'px';
   if (progress < 2000) {
      window.requestAnimationFrame(step);
   }
}

window.requestAnimationFrame(step);

我在这里得到这段代码:https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

我想问的是timestamp上的function step(timestamp) {...}参数。

我不明白这个timestamp如何获得价值,为什么? 因为我没有看到任何分配值。

1 个答案:

答案 0 :(得分:0)

requestAnimationFrame函数内部看起来有点模糊:

function requestAnimationFrame(func) {
    waitForNextAnimationFrame();
    func(getCurrentTime());
}

正在发生的事情是requestAnimationFrame将您的函数作为输入,然后,稍后使用参数调用它。