gpt4 book ai didi

javascript - requestAnimationFrame 在被函数调用之前运行

转载 作者:行者123 更新时间:2023-11-30 19:34:24 28 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 和 requestAnimationFrame 制作一个简单的计时器(从 0 开始计数)。单击某些内容时,我想从 0 开始计时。目前我的代码在单击按钮时显示计时器,但在我看来 requestAnimationFrame 在函数被调用之前就已经在运行了。如果您在网页上加载代码并等待几秒钟,然后单击按钮,您会看到计时器不是从 0 开始,而是从页面首次加载后的秒数开始。我不知所措,谷歌搜索并没有帮助我弄清楚为什么/如何在函数被调用之前计时器开始计数。

我当前的代码:

<div class="time">
Time: <label id="labelTime"></label>
</div>
<button id="button">Click me</button>
<script>
const button = document.getElementById('button');
button.addEventListener('click', clickButton);

function clickButton() {
runTimer();
}

function runTimer() {
let rAF_ID;

let rAFCallback = function(callback) {
let count = callback;

let s = Math.floor((count / 1000) % 60).toString().padStart(2, '0');
let m = Math.floor((count / 60000) % 60);

document.getElementById('labelTime').innerHTML = m + ":" + s;
rAF_ID = requestAnimationFrame(rAFCallback);
}
rAF_ID = requestAnimationFrame(rAFCallback);
}
</script>

最佳答案

传递给 rAFCallback 函数的 timestamp (DOMHighResTimeStamp) 值不是从动画第一次运行时开始的,而是有一个“时间起源”因上下文而异。

https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp

  • If the script's global object is a Window, the time origin is determined as follows:

    • If the current Document is the first one loaded in the Window, the time origin is the time at which the browser context was created.
    • If during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable.
    • If neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current Document took place.
  • If the script's global object is a WorkerGlobalScope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created.
  • In all other cases, the time origin is undefined.

因此,如果您想从动画开始时获取增量时间值,您需要自己执行此操作,如下所示:

let timestampAtStart = null;
let lastRequestId = null;

function myAnimateFunction( timestamp ) {
if( !timestampAtStart ) {
timestampAtStart = timestamp;
}

let timeSinceStart = timestamp - timestampAtStart;

console.log( timeSinceStart );

lastRequestId = window.requestAnimationFrame( myAnimateFunction );
}

function startAnimation() {

if( lastRequestId ) window.cancelAnimationFrame( lastRequestId );

timestampAtStart = null;

lastRequestId = window.requestAnimationFrame( myAnimateFunction );
}

关于javascript - requestAnimationFrame 在被函数调用之前运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095782/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com