浅析防抖(debounce)和节流(throttle)

在平常的项目开发当中,我们经常会使用到防抖(debounce)或者节流(throttle)对项目的性能进行优化。

防抖(debounce)

防抖就是在规定的一段时间内,只执行最后一次被事件触发的方法。举个栗子,在两秒内,有一个方法被事件触发了,如果在两秒内这个事件没有被再次触发,则会执行这个方法。如果两秒内这个事件被再次触发的话,则会重新计算该方法执行的时间。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖(debounce)</title>
</head>

<body>
    <input type="text" id="ipt">
    <script>
        const ipt = document.getElementById('ipt')

        function myipt(val) {
            console.log(`输出的内容:${val}`)
        }

        function debounce(fun, time) {
            let timer
            return function (arg) {//闭包的作用:延长作用域,缓存变量,函数复用
                clearTimeout(timer)//清除上一个定时器
                timer = setTimeout(() => {
                    fun.call(this, arg)
                }, time);
            }
        }

        let debounceIpt = debounce(myipt, 500)

        ipt.addEventListener('keyup', function (e) {
            debounceIpt(e.target.value)
        })
    </script>
</body>

</html>

节流(throttle)

节流就是在规定时间内,重复触发事件,但是只执行第一次触发事件时候的方法。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流(throttle)</title>
</head>

<body>
    <input type="text" id="ipt">
    <script>
        const ipt = document.getElementById('ipt')

        function myipt(val) {
            console.log(`输出的内容:${val}`)
        }

        function throttle(fun, time) {
            let timer = null
            return function (arg) {
                if (!timer) {
                    timer = setTimeout(() => {
                        fun.call(this, arg)
                        timer = null
                    }, time);
                }

            }
        }

        let debounceIpt = throttle(myipt, 1000)

        ipt.addEventListener('keyup', function (e) {
            debounceIpt(e.target.value)
        })
    </script>
</body>

</html>

使用场景

防抖:一般在项目中,用户在输入框中输入值时会频繁发起请求,可以用防抖来优化。
节流:鼠标不断点击触发事件,可以用节流来只让规定时间内第一次点击有效。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。