javascript - 时间戳的值从何而来?
问题描述
下面的代码片段来自 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>
解决方案
当你console.log(timestamp)
在draw()
函数内部时,你会看到它第一次被调用的时间戳是未定义的,但之后的所有调用都有一个值。
这是因为draw()
函数的最后一行,它draw
作为回调函数传递给requestAnimationFrame()
函数。
requestAnimationFrame()
内部调用draw()
并传递时间戳参数。
推荐阅读
- kotlin - 如果为空,如何将新列表分配给可为空的字段,或者只是将元素添加到 Kotlin 中的现有列表?
- reactjs - 带有 NextJs 的 ModuleParseError
- ansible - 在 Ansible 中覆盖默认变量的属性
- java - Android:手机重启后设置闹钟/提醒
- android - 电话不显示反应原生(世博会)上的所有文本
- java - Log Miner 无法捕获数据
- sql - SQL, query to check and list distinct entries that occur in another table within a specific time frame
- flutter - Iterable 具有价值,但是当我尝试将其传递给函数或将其转换为列表时,它似乎为空
- java - 我有一个 ArrayIndexOutOfBoundsException 我不知道为什么
- angular - 多组件双向绑定数据传输