首页 > 解决方案 > 时间戳的值从何而来?

问题描述

下面的代码片段来自 MDN ( https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/loops-and-intervals/simple-raf-spinner.html )。我只是无法理解函数draw()的参数'timestamp',值来自哪里?

我尝试在控制台中检查它,rotateCount 计算正确,startTime 也可以,但没有定义时间戳。

<script>
      // Store reference to the div element, create a rotate counter and null startTime
      // and create an uninitialized variable to store the requestAnimationFrame() call in
      const spinner = document.querySelector('div');
      let rotateCount = 0;
      let startTime = null;
      let rAF;
      // Create a draw() function
      function draw(timestamp) {
        if(!startTime) {
         startTime = timestamp;
        }
        rotateCount = (timestamp - startTime) / 3;

        // If rotateCount gets over 359, set it to 'remainder of dividing by 360'
        if(rotateCount > 359) {
          rotateCount %= 360;
        }
        // Set the rotation of the div to be equal to rotateCount degrees
        spinner.style.transform = 'rotate(' + rotateCount + 'deg)';

        // Call the next frame in the animation
        rAF = requestAnimationFrame(draw);
      }
      draw();
    </script>

标签: javascript

解决方案


当你console.log(timestamp)draw()函数内部时,你会看到它第一次被调用的时间戳是未定义的,但之后的所有调用都有一个值。

这是因为draw()函数的最后一行,它draw作为回调函数传递给requestAnimationFrame()函数。

requestAnimationFrame()内部调用draw()并传递时间戳参数。


推荐阅读