什么是防抖和节流?有什么区别?如何实现?

 

作⽤:本质上是优化⾼频率执⾏代码的⼀种⼿段!

如:浏览器的 resize、scroll、keypress、mousemove 等事件在触发时,会不断地调⽤绑定在事件上的回调函数,极⼤地浪费资源,降低前端性能.

为了优化体验,需要对这类事件进⾏调⽤次数的限制,对此我们就可以采⽤debounce(防抖)和throttle(节流)的⽅式来减少调⽤频率.

定义:

         节流: n 秒内只运⾏⼀次,若在 n 秒内重复触发,只有⼀次⽣效

         防抖: n 秒后在执⾏该事件,若在 n 秒内被重复触发,则重新计时.

相同点:

  • 都可以通过使⽤ setTimeout
  • 实现⽬的都是,降低回调执⾏频率。节省计算资源

不同点:

  • 函数防抖,在⼀段连续操作结束后,处理回调,利⽤clearTimeout和 setTimeout实现。
  • 函数节流,在⼀段连续操作中,每⼀段时间只执⾏⼀次,频率较⾼的事件中使⽤来提⾼性能
  • 函数防抖关注⼀定时间连续触发的事件,只在最后执⾏⼀次,⽽函数节流⼀段时间内只执⾏⼀次

例如,都设置时间频率为500ms,在2秒时间内,频繁触发函数,节流,每隔 500ms 就执⾏⼀次。防抖,则不管调动多少次⽅法,在2s后,只会执⾏⼀次

应⽤场景

防抖在连续的事件,只需触发⼀次回调的场景有:

  • 搜索框搜索输⼊。只需⽤户最后⼀次输⼊完,再发送请求
  • ⼿机号、邮箱验证输⼊检测
  • 窗⼝⼤⼩resize。只需窗⼝调整完成后,计算窗⼝⼤⼩。防⽌重复渲染。

节流在间隔⼀段时间执⾏⼀次回调的场景有:

  • 滚动加载,加载更多或滚到底部监听
  • 搜索框,搜索联想功能

代码实现

节流

完成节流可以使⽤时间戳与定时器的写法

使⽤时间戳写法,事件会⽴即执⾏,停⽌触发后没有办法再次执⾏

function throttled1(fn, delay = 500) {
 let oldtime = Date.now() 
   return function (...args) {
      let newtime = Date.now() 
       if (newtime - oldtime >= delay) { 
        fn.apply(null, args) 
           oldtime = Date.now()
   }
  }
}

使⽤定时器写法,delay毫秒后第⼀次执⾏,第⼆次事件停⽌触发后依然会再⼀次执⾏

function throttled2(fn, delay = 500) { 
   let timer = null 
    return function (...args) { 
        if (!timer) {
           timer = setTimeout(() => { 
           fn.apply(this, args)
               timer = null
           }, delay);
  }
 }
}

可以将时间戳写法的特性与定时器写法的特性相结合,实现⼀个更加精确的节流。实现如下

function throttled(fn, delay) {
 let timer = null
 let starttime = Date.now() 
  return function () { 
          let curTime = Date.now() // 当前时间 
          let remaining = delay - (curTime - starttime) // 从上⼀次到现在,还剩下多少多余时间 
          let context = this 
          let args = arguments
          clearTimeout(timer)
          if (remaining <= 0) {
              fn.apply(context, args) 
              starttime = Date.now() } else {
                timer = setTimeout(fn, remaining);
    }
  }
}

防抖

简单版本的实现

function debounce(func, wait) { 
    let timeout;  
      return function () { 
          let context = this; // 保存this指向 
          let args = arguments; // 拿到event对象 
          clearTimeout(timeout)
          timeout = setTimeout(function(){ 
              func.apply(context, args) 
        },wait); 
    }
 }

防抖如果需要⽴即执⾏,可加⼊第三个参数⽤于判断,实现如下:

function debounce(func, wait, immediate) { 
   let timeout; 
    return function () { 
          let context = this; 
          let args = arguments;  
          if (timeout) clearTimeout(timeout); // timeout 不为null 
          if (immediate) {
             let callNow = !timeout; // 第⼀次会⽴即执⾏,以后只有事件执⾏后才会再次触发 
            timeout = setTimeout(function () { 
             timeout = null; 
          }, wait) if (callNow) { 
           func.apply(context, args)
  }
} 
else { 
   timeout = setTimeout(function () { 
    func.apply(context, args) }, wait);
  }
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端践行者-Mr鹏帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值