window.requestAnimationFrame

101 阅读1分钟

image.png

用法

requestAnimationFrame是请求动画帧,它是浏览器的一个宏任务,简单的说,这个api主要是用来做动画的


       requestAnimationFrame()

        // 无法保证定时器时间间隔
        setInterval(function () {}, 17)

        // 不是由js的时间间隔来控制的,而是由系统时间间隔来解决的,时间间隔就是16.67
        // requestAnimationFrame也有返回值,返回值是一个整数,主要是它的身份标识
        var timer1 = requestAnimationFrame(function () {
            console.log(timer1)
        })

        var timer2 = requestAnimationFrame(function () {
            console.log(timer2)
        })

        var timer3 = requestAnimationFrame(function () {
            console.log(timer3)
        })

        cancelAnimationFrame(timer1)

在动画中的应用

<!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: 0; height: 12px; line-height: 12px; background-color: red">0%</div>
    </body>
    <script>
           // requestAnimationFrame与setTimeout的用法相似的,只是前者的时间间隔是固定的16.67ms,并且它的时间间隔不由js来决定,而是由系统来决定的。
            test.onclick = function () {
            var timer = requestAnimationFrame(function fn() {
                if (parseInt(test.style.width) < 300) {
                    test.style.width = parseInt(test.style.width) + 3 + 'px'
                    test.innerHTML = parseInt(test.style.width) / 3 + '%'
                    timer = requestAnimationFrame(fn)
                } else {
                    cancelAnimationFrame(timer)
                }
            })
        }
    
        // 使用setInterval
        // test.onclick = function () {
        //     var timer = setInterval(function () {
        //         if (parseInt(test.style.width) < 300) {
        //             test.style.width = parseInt(test.style.width) + 3 + 'px'
        //             test.innerHTML = parseInt(test.style.width) / 3 + '%'
        //         } else {
        //             clearInterval(timer)
        //         }
        //     }, 17)
        // }

        // 使用setTimeout
        // test.onclick = function () {
        //     var timer = setTimeout(function fn() {
        //         if (parseInt(test.style.width) < 300) {
        //             test.style.width = parseInt(test.style.width) + 3 + 'px'
        //             test.innerHTML = parseInt(test.style.width) / 3 + '%'
        //             timer = requestAnimationFrame(fn)
        //         } else {
        //             cancelAnimationFrame(timer)
        //         }
        //     }, 17)
        // }
    </script>
</html>