JS常用工具函数-节流和防抖

节流和防抖是属于面试和日常开发过程中常见的问题

函数防抖(debounce)

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。用户在不断输入值时,用防抖来节约请求资源。

场景:监听input的每一次onkeyup事件请求,调用接口做模糊匹配。在频繁的输入中,如果每次都去调用接口,不仅会造成资源的浪费,而且在实际场景中,用户输入完成后再去请求。

export const debounce = (fn, delay) => {
  let delays = delay || 200
  let timer
  return function () {
    let th = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function () {
      timer = null
      fn.apply(th, args)
    }, delays)
  }
}
prevCheck: debounce(function () {
      /*
      * */
}, 800),

函数节流(throttle)

规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

场景:列表页切换,请求接口返回列表数据。为了限制短时间内频繁请求大量列表数据,规定单位时间内才可以触发

export const throttle = (fn, t) => {
  let last
  let timer
  let interval = t || 500
  return function () {
    let args = arguments
    let now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}
prevCheck: throttle(function () {
      /*
      * */
}, 800),

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值