函数防抖和函数节流

函数防抖(debounce)

当调用动作过n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间

如果有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时如果又有人进电梯了(在10秒内再次触发该事件),我们又得等10秒再出发(重新计时)

函数节流(throttle) 

预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期 

保证如果电梯第一个人进来后,10秒后准时运送一次,这个时间从第一个人上电梯开始计时,不等待,如果没有人,则不运行

 函数防抖(debounce)

function _debounce(fn,wait){
    var timer = null;
    return function(){
        clearTimeout(timer)  // 清除未执行的代码,重置回初始化状态
        timer = setTimeout(()=>{
            fn()
        },wait)
    }
}

function fn(){
    console.log(1)
}
window.onscroll = _debounce(fn,500)

优化

       function _debounce(fn,wait,time){
            var timer = null;
            var pre = null;
            return function (){
                var now = +new Date();
                if(!pre) pre = now
                 if(now - pre > time){
              //当上一次执行的时间与当前的时间差大于设置的执行间隔时长的话,就主动执行一次
                    clearTimeout(timer);
                    fn();
                    pre = now;
                }else{
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        fn();
                    },wait)
                }
            }
        }
        function fn(){
            console.log(1)
        }
        
        window.onscroll = _debounce(fn,500,2000)

函数节流(throttle)

      function _throttle(fn, time) {
           let timer, firstTime = true;
           return function (){
               if(firstTime) {
                   fn();
                  firstTime = false
               }
               if(timer){return false}
                timer = setTimeout(function(){
                    clearTimeout(timer)
                    fn();  
                    timer = null    
                },500)
           }
       }
       function fn(){
    console.log(1)
}
window.onscroll = _throttle(fn,500)

猜你喜欢

转载自blog.csdn.net/weixin_41910848/article/details/82151420