H5新特性——requestAnimationFrame

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值