requestAnimationFrame与setTimeout动画对比

1,771 阅读1分钟

通过在vue3中用jsx的语法对比requestAnimationFrame和setTimeout

  • requestAnimationFrame浏览器自动控制运动的频率
  • setTimeout根据实际情况,一般人肉眼能识别的频率是60桢每秒,根据实际情况计算

setTimeout动画

    setup() {
        const boxRef = ref()
        nextTick(() => {
            let currWidth = 100
            const maxWidth = 600
            const animate = () => {
                currWidth += 3
                boxRef.value.style.width = currWidth + 'px'
                if(currWidth < maxWidth) {
                    setTimeout(animate, 16.7)
                    //计算动画进行的频率,一般人肉眼看到的是60桢每秒,需要自己控制
                }
            }
            animate()
        })

        return () => {
            return (
                <div>
                    <div ref={boxRef} className='box'></div>
                </div>
            )
        }
    }

requestAnimationFrame动画

    setup() {
        const boxRef = ref()
            const maxWidth = 600
            const animate = () => {
                currWidth += 3
                boxRef.value.style.width = currWidth + 'px'
                if(currWidth < maxWidth) {
                    requestAnimationFrame(animate)
                    //不用自己控制频率,直接控制判断条件,浏览器自动执行
                }
            }
            animate()
        })

        return () => {
            return (
                <div>
                    <div ref={boxRef} className='box'></div>
                </div>
            )
        }
    }