Javascript 时间戳的值来自哪里?
下面的代码片段来自MDN()。我就是不明白函数draw()的参数'timestamp',这个值从哪里来 我试图在控制台中检查它,rotateCount计算正确,startTime也可以,但时间戳没有定义Javascript 时间戳的值来自哪里?,javascript,Javascript,下面的代码片段来自MDN()。我就是不明白函数draw()的参数'timestamp',这个值从哪里来 我试图在控制台中检查它,rotateCount计算正确,startTime也可以,但时间戳没有定义 <script> // Store reference to the div element, create a rotate counter and null startTime // and create an uninitialized variable
<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>
//存储对div元素的引用,创建一个旋转计数器和null startTime
//并创建一个未初始化的变量来存储requestAnimationFrame()调用
常量微调器=document.querySelector('div');
设rotateCount=0;
让startTime=null;
让英国皇家空军;
//创建draw()函数
函数绘制(时间戳){
如果(!开始时间){
开始时间=时间戳;
}
rotateCount=(时间戳-开始时间)/3;
//如果rotateCount超过359,则将其设置为“除以360的余数”
如果(旋转计数>359){
旋转计数%=360;
}
//将div的旋转设置为等于rotateCount度数
spinner.style.transform='rotate('+rotateCount+'deg');
//调用动画中的下一帧
rAF=请求动画帧(绘制);
}
draw();
根据
回调函数只传递一个参数,即
DOMHighResTimeStamp与performance.now()返回的类似,
指示requestAnimationFrame()开始运行的时间点
执行回调函数
无论何时调用draw
,它都会将第一个参数传递给draw
这有两个地方:
和draw()代码>未定义的位置
- 在将
本身作为参数传递到此处后,在draw
(内置于浏览器中)下面的代码中:requestAnimationFrame
requestAnimationFrame(draw)
draw()
时没有它。但当你这么做的时候:
requestAnimationFrame(draw)
您将draw()
作为requestAnimationFrame()
的回调传递requestAnimationFrame
作为您提供给它的回调的第一个参数。无论何时为您调用draw()
,它都会发生。请参见窗口上的此页。requestAnimationFrame
,特别是第一个水平条前面的这一段:
回调方法传递一个参数,即DOMHighResTimeStamp
,该参数指示当前时间(基于自时间原点起的毫秒数)。当由requestAnimationFrame()
排队的回调开始在单个帧中触发多个回调时,每个回调都会收到相同的时间戳,即使在计算之前每个回调的工作负载时时间已经过去。此时间戳是十进制数,以毫秒为单位,但最小精度为1ms(1000µs)
因此,
时间戳
由函数末尾的窗口传递。requestAnimationFrame(draw)
。手动调用draw()
时,它是未定义的。当在requestAnimationFrame
内部调用它时,情况并非如此,后者作为回调(时间戳)传递参数。来自
回调方法传递一个参数,即
DOMHighResTimeStamp,指示当前时间(基于
自时间原点起的毫秒数)
当您在draw()
函数中console.log(timestamp)
时,您将看到它第一次被调用时,时间戳是未定义的,但之后的所有调用都有一个值
这是因为draw()
函数中的最后一行将draw
作为回调函数传递给requestAnimationFrame()
函数
requestAnimationFrame()
内部调用draw()
并传递时间戳参数。可能是这样吗<代码>变量日期=新日期();var timestamp=date.getTime()代码>阅读requestAnimationFrame
的文档。就在描述里说的谢谢大家,明白了。问题结束。
requestAnimationFrame(draw)