setTimeout跟requestAnimationFrame的区别
- setTimeout是异步执行的,遇到同步任务,他不会立即执行,requestAnimationFrame是立即执行的
- requestAnimationFrame在页面后台运行的时候会停止运行,减少dom的损耗
- requestAnimationFrame根据屏幕分辨率来运行动画,匀速动画,1s中执行60次,60hz,settimeout可能会丢帧
用requestAnimationFrame模拟进度条
<style>
.box {
width: 1px;
height: 10px;
background-color: orange;
}
</style>
<body>
<div class="box"></div>
<div class="progress">当前进度<span>0%</span></div>
<script>
function render () {
let dom = document.getElementsByClassName('box')[0]
let progress = document.getElementsByClassName('progress')[0].getElementsByTagName('span')[0]
dom.style.width = dom.clientWidth + 1 + 'px';
progress.innerHTML = parseInt(dom.clientWidth /2) + '%'
if (parseInt(dom.style.width) < 200) {
requestAnimationFrame(render)
}
}
requestAnimationFrame(render)
</script>
</body>


网友评论