requestAnimationFrame 介绍
和定时器 setTimeout()、setInterval() 是相关的,因为requestAnimationFrame 是H5新增的API,是为了解决定时器时间间隔不稳定的问题,
屏刷新频率是 60HZ ==> 也就是每秒60次. ==> 相当于1000毫秒60次 = 16.67ms一次。也就是说每16.67毫秒刷新一次是浏览器显示的最大刷新频率。我们一般设置16或者17 接近这个频率。
setInterval(()=>{
// 是异步API,必须要等待同步任务后执行,具体说要等待微任务完成才会执行。
// 所以没有办法精准的定位这个时间 17,
// 所以h5 新增的 requestAnimationFrame
},17)
requestAnimationFrame 的调用不是由JS来控制的,而且由系统的时间间隔来解决的。用法和setTimeout是类似的。不一样的是当前的时间间隔是定死的,你不能控制而是有系统控制。
var timer = requestAnimationFrame(()=>{
console.log(timer )
})
cancelAnimationFrame(timer) // 清空
兼容性
requestAnimationFrame 是H5新增的特性,遇到不兼容的情况如下解决
if(!window.requestAnimationFrame){
requestAnimationFrame = function(fn){
setTimeout(fn,17)
}
}
应用
进度条的处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test" style="width: 0px; height: 25px; line-height: 25px;background-color: aquamarine;">
0%
</div>
</body>
<script>
let test = document.getElementById("test")
// test.onclick = function () {
// var timer = setInterval(function () {
// if (parseInt(test.style.width) < 500) {
// test.style.width = parseInt(test.style.width) + 5 + "px";
// test.innerHTML = parseInt(test.style.width) / 5 + "%"
// } else {
// clearInterval(timer)
// }
// }, 17)
// }
// 或者用 setTimeout
// test.onclick = function () {
// var timer = setTimeout(function fn() {
// if (parseInt(test.style.width) < 500) {
// test.style.width = parseInt(test.style.width) + 5 + "px";
// test.innerHTML = parseInt(test.style.width) / 5 + "%"
// timer = setTimeout(fn,17) // 因为 setTimeout 只执行一次,所以要重新赋值
// } else {
// clearTimeout(timer)
// }
// }, 17)
// }
// 使用 requestAnimationFrame
test.onclick = function () {
var timer = requestAnimationFrame(function fn() {
if (parseInt(test.style.width) < 500) {
test.style.width = parseInt(test.style.width) + 5 + "px";
test.innerHTML = parseInt(test.style.width) / 5 + "%"
timer = requestAnimationFrame(fn) // 因为 setTimeout 只执行一次,所以要重新赋值
} else {
cancelAnimationFrame(timer)
}
})
}
</script>
</html>