js 的函数节流和防抖的区别

区别:

函数节流是指一定时间内js方法只跑一次。比如人的眨眼睛,就是一定时间内眨一次。

函数防抖是指频繁触发的情况下,只有足够的空间时间,才执行代码一次。比如坐公交,就是一定时间内,如果有人陆续刷卡上车,司机就不会开车。只有别人没刷卡了,司机才开车。

一、节流: 控制高频事件执行次数    

应用场景: 多数在监听页面元素滚动事件的时候会用到。因为滚动事件,是一个高频触发的事件

 <style>
        body {
            height: 2000px;
        }
 </style>

<script>
   window.onscroll = throttle(function () {
        console.log("节流");
    }, 500)
    function throttle(fn, delay) {
        let flag = true;
        return function () {
            if (flag) {
                setTimeout(() => {
                    fn.call(this);
                    flag = true;
                }, delay);
            }
            flag = false;
        }
    }  
</script>

二、防抖:用户触发事件过于频繁,只要最后一次事件的操作

应用场景:最常见的就是用户注册时候手机号码验证等,只有等用户输入完毕后,前端才需要检查格式是否正确,如果不正确,再弹框提示。

<body>
    <input type="text">
</body>

<script>
    let inp = document.querySelector('input');
    inp.oninput = debounce(function () {
        console.log(this.value);
    }, 500)

    function debounce(fn, delay) {
        let t = null;
        return function () {
            if (t !== null) {
                clearTimeout(t);
            }
            t = setTimeout(() => {
                fn.call(this);
            }, delay)
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/Tianxiaoxixi/article/details/125053250