刚接触到requestAnimationFrame我也很奇怪,有了setTimeout、 setInterval为什么还要用requestAnimationFrame呢?
requestAnimationFrame 比起 setTimeout、setInterval的优势主要有两点:
1、requestAnimationFrame 会把每一帧中的所有DOM操作集中起来,在一次重绘或回流中就完成,并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率,一般来说,这个频率为每秒60帧。
2、在隐藏或不可见的元素中,requestAnimationFrame将不会进行重绘或回流,这当然就意味着更少的的cpu,gpu和内存使用量。
下面我们分别用三个函数分别来写个进度条:
先画个宽度为0的div
<div id="loading" style="width: 0px;height: 30px;line-height: 30px;background: cadetblue;border-radius: 5px;padding:2px;color: #fff;text-align: center;margin-left: 20%">0%</div>
用setInterval
<script>
loading.onclick=()=>{
let timer=setInterval(function (){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
}else {
clearInterval(timer)
}
})
}
</script>
用setTimeout
<script>
loading.onclick=()=>{
let timer=setTimeout(function fn(){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
setTimeout(fn,17)
}else {
clearTimeout(timer)
}
},17)
}
</script>
用requestAnimationFrame
<script>
loading.onclick=()=>{
let timer=requestAnimationFrame(function fn(){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
requestAnimationFrame(fn,17)
}else {
cancelAnimationFrame(timer)
}
},17)
}
</script>
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div id="loading" style="width: 0px;height: 30px;line-height: 30px;background: cadetblue;border-radius: 5px;padding:2px;color: #fff;text-align: center;margin-left: 20%">0%</div>
<script>
//用setInterval
/*loading.onclick=()=>{
let timer=setInterval(function (){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
}else {
clearInterval(timer)
}
})
}*/
//用setTimeout
/*loading.onclick=()=>{
let timer=setTimeout(function fn(){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
setTimeout(fn,17)
}else {
clearTimeout(timer)
}
},17)
}*/
//用requestAnimationFrame
loading.onclick=()=>{
let timer=requestAnimationFrame(function fn(){
if(parseInt(loading.style.width)<500){
loading.style.width=parseInt(loading.style.width)+2+"px"
loading.innerHTML=parseInt(loading.style.width)/5+'%'
requestAnimationFrame(fn,17)
}else {
cancelAnimationFrame(timer)
}
},17)
}
</script>
</body>
</html>