为啥一般使用requestAnimationFrame 代替setTimeout
时间: 2023-12-19 07:31:34 浏览: 32
使用requestAnimationFrame代替setTimeout的原因有以下几点:
1. requestAnimationFrame的执行时间是由浏览器决定的,它会根据浏览器的刷新频率来决定回调函数的执行时间,因此可以保证动画的流畅性和性能。
2. 当页面处于未激活状态时,requestAnimationFrame会停止执行,从而节省了CPU、GPU和电池的能量消耗。
3. requestAnimationFrame会自动进行函数节流,如果浏览器的刷新频率为60Hz,那么回调函数也会以60Hz的频率执行,这样可以避免过度绘制和卡顿现象的发生。
以下是一个使用requestAnimationFrame实现动画的例子:
```javascript
// 获取元素
var box = document.getElementById('box');
// 定义变量
var start = null;
var end = null;
var duration = 1000; // 动画持续时间
// 定义动画函数
function animate(timestamp) {
if (!start) start = timestamp;
end = start + duration;
var progress = Math.min((timestamp - start) / duration, 1); // 计算动画进度
box.style.left = progress * 500 + 'px'; // 修改元素的left属性
if (progress < 1) {
window.requestAnimationFrame(animate); // 继续执行动画
}
}
// 启动动画
window.requestAnimationFrame(animate);
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)