函数防抖与函数节流

概念

函数防抖(debounce)

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

函数节流(throttle)

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

函数节流(throttle)

函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。

比如如下的情况:

  • window对象的resize、scroll事件
  • 拖拽时的mousemove事件
  • 文字输入、自动完成的keyup事件

可以拿我们平时坐电梯为例来形象地表述二者的区别

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

函数节流

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

实现

函数防抖(debounce)

function _debounce(fn,wait){
    var timer = null;
    return function(){
        clearTimeout(timer)
        timer = setTimeout(()=>{
            fn()
        },wait)
    }
}

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

但是,仔细想想,上面的实现方式还是有一定的缺点。如果页面很长,我们一直在滚动页面,那_log方法就一直不会被执行。所以我们可以升级一下上述的防抖方法。

function _debounce(fn,wait,time){
    var previous = null; //记录上一次运行的时间
    var timer = null;

    return function(){
        var now = +new Date();

        if(!previous) previous = now;
        //当上一次执行的时间与当前的时间差大于设置的执行间隔时长的话,就主动执行一次
        if(now - previous > time){
            clearTimeout(timer);
            fn();
            previous = now;// 执行函数后,马上记录当前时间
        }else{
            clearTimeout(timer);
            timer = setTimeout(function(){
                fn();
            },wait);
        }
    }
}
function _log(){
    console.log(1)
}
window.onscroll = _debounce(_log,500,2000)

函数节流(throttle)

function _throttle(fn, time) { 

  let _self = fn, 
      timer,  
      firstTime = true //记录是否是第一次执行的flag

  return function() { 
    let args = arguments, //解决闭包传参问题
        _me = this //解决上下文丢失问题

    if(firstTime) { //若是第一次,则直接执行
      _self.apply(_me, args)
      return firstTime = false
    }
    if(timer) { //定时器存在,说明有事件监听器在执行,直接返回
      return false
    }

    timer = setTimeout(function() { 
      clearTimeout(timer)
      timer = null
      _self.apply(_me, args)
    }, time || 500)
  }
}

function _log(){
    console.log(1)
}
window.onscroll = _throttle(_log,500)

ES6中的函数防抖和函数节流

//函数节流
const throttle = (fun,  delay) => {
    let last = null;
    return () => {
        const now = + new Date();
        if (now - last > delay) {
            fun();
            last = now;
        }
    }
}
//实例
const throttleExample  = throttle(() => console.log(1), 1000);
//调用
throttleExample();
throttleExample();
throttleExample();
//函数防抖
const debouce = (fun, delay) => {
    let timer = null;
    return () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fun();
        }, delay);
    }
}
//实例
const debouceExample = debouce(() => console.log(1), 1000);
//调用
debouceExample();
debouceExample();
debouceExample();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • debounce -- 函数防抖,throttle -- 函数节流都是在JavaScript中可以限制函数发生频率...
    Quilljou阅读 3,229评论 0 3
  • 前言 在类似scroll、resize事件中执行大量DOM操作或者计算时,就会出现再次触发事件而上一次事件中的DO...
    王阿王阅读 4,583评论 0 2
  • 函数节流 还记得上篇文章中说到的图片懒加载吗?我们在文章的最后实现了一个页面滚动时按需加载图片的方式,即在触发滚动...
    柏丘君阅读 7,921评论 1 19
  • 函数节流(throttle)与 函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致...
    _Dot912阅读 4,189评论 0 6
  • 我们相识的曾经, 笔尖写不下温存。 我带着你最初的纯, 默默数着岁月的年轮。 我已走过了曾经的曾经, 时光刻下了深...
    南宫诗萌阅读 1,675评论 2 3

友情链接更多精彩内容