美文网首页
requestAnimationFrame实现动画

requestAnimationFrame实现动画

作者: 盖子pp | 来源:发表于2022-09-05 11:38 被阅读0次

setTimeout跟requestAnimationFrame的区别

  1. setTimeout是异步执行的,遇到同步任务,他不会立即执行,requestAnimationFrame是立即执行的
  2. requestAnimationFrame在页面后台运行的时候会停止运行,减少dom的损耗
  3. 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>
image.png
image.png

相关文章

网友评论

      本文标题:requestAnimationFrame实现动画

      本文链接:https://www.haomeiwen.com/subject/hvivnrtx.html