关于防抖和节流

        防抖:

                只对最后一次操作发起请求

        节流:

                控制触发的请求次数

例子:

        防抖措施:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <input id="input" type="text">

    <script>

        let domElement = document.getElementById('input')

        // 此时会产生数据抖动的情况,每当往input框里输入一个东西,都会打印一次value
            // 会触发多次无用的请求
        // domElement.oninput = function () {
        //     console.log(this.value);
        // }

        // 防抖:只对最后一次输入发起请求
            // 封装 防抖函数 debounce
        function debounce(fn, delay) {
            let t = null
            return function () {
                if (t !== null) {
                    clearTimeout(t)
                }
                t = setTimeout(() => {
                    // console.log('setTimeout - this', this); // 指向 input 标签
                    fn.call(this) 
                }, delay)
            }
        }

        domElement.oninput = debounce(function () {
            // console.log('debounce - fn - this', this); // 指向 window 全局对象
            console.log(this.value);
        }, 666)

    </script>
    
</body>
</html>

        节流措施:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <div 
        id="div"
        style="width:6666px;height:666px;background-color:aqua;">
    </div>

    <script>

        // 滚动一次滚动条触发了多次时间,消耗性能
        // window.onscroll = function () {
        //     console.log('滚动条滚动了')
        // }

        // 节流:控制触发次数
        function throttle(fn, delay) {
            let flag = true
            return function () {
                if (flag) {
                    setTimeout(() => {
                        fn.call(this)
                        flag = true
                    }, delay)
                }
                flag = false
            }
        }

        window.onscroll = throttle(function () {
            console.log('滚动条滚动了')
        }, 666)

    </script>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值