用 requestAnimationFrame 实现正计时
时间: 2023-12-20 12:32:53 浏览: 40
要使用`requestAnimationFrame`实现正计时,你可以使用递归函数来不断更新计时器并在每一帧更新显示的时间。下面是一个简单的示例代码:
```javascript
let startTime;
let elapsedTime = 0;
function startTimer() {
startTime = Date.now();
requestAnimationFrame(updateTimer);
}
function updateTimer() {
const currentTime = Date.now();
elapsedTime = currentTime - startTime;
// 将毫秒转换为秒和毫秒
const seconds = Math.floor(elapsedTime / 1000);
const milliseconds = elapsedTime % 1000;
// 在页面上显示时间
document.getElementById('timer').textContent = `${seconds}.${milliseconds}`;
// 继续更新计时器
requestAnimationFrame(updateTimer);
}
// 启动计时器
startTimer();
```
在上面的代码中,`startTimer`函数用于启动计时器。它记录了开始时间,并调用`updateTimer`函数来更新计时器。
`updateTimer`函数首先获取当前时间,并计算已经过去的时间。然后,它将毫秒转换为秒和毫秒,并将其显示在页面上。
最后,`updateTimer`函数通过调用`requestAnimationFrame`来不断更新计时器。这样可以确保计时器在每一帧都得到更新,以获得更平滑的效果。
请注意,上述代码中的`timer`是一个具有相应`id`的HTML元素,用于显示计时器的值。你需要在页面上创建一个具有相应`id`的元素,并将其替换为你自己的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)