Skip to content

防抖 & 节流

debounce(防抖)

防抖:指函数触发后,等待一段时间,再运行函数,如果这段时间内事件再次被触发,则重新计时。

使用场景(短时间内高频触发):输入框实时搜索,窗口大小调整 ……

巧记

回城

ts
function debounce(fn: Function, delay: number = 500) {
  let timer: ReturnType<typeof setTimeout>
  return function (...args: any[]) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      // @ts-ignore
      fn.apply(this, args)
    }, delay)
  }
}
js
const debounce = (func, delay = 500) => {
  let timer
  return function (...args) {
    const context = this // 执行上下文
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(context, args)
    }, delay)
  }
}

throttle(节流)

节流:在一定时间间隔中,只执行一次函数。

使用场景(高频触发):滚动事件,鼠标移动 ……

巧记

技能 cd

ts
function throttle(fn: Function, wait: number = 1000) {
  let lastTime = 0
  return function (...args: any[]) {
    const now = Date.now()
    if (lastTime === 0 || now - lastTime > wait) {
      // @ts-ignore
      fn.apply(this, args)
      lastTime = now
    }
  }
}
js
function throttle(func, delay = 500) {
  let isWait = false // 是否需要等待标识
  let waitingArgs = null // 等待期间的新增参数
  let context // 执行上下文

  function timeoutFunc() {
    if (waitingArgs === null) {
      isWait = false
    } else {
      func.apply(context, waitingArgs)
      waitingArgs = null
      setTimeout(timeoutFunc, delay)
    }
  }

  return function (...args) {
    context = this
    if (isWait) {
      waitingArgs = args // 更新 args
      return
    }
    func.apply(context, args) // 第一次执行
    isWait = true
    setTimeout(timeoutFunc, delay)
  }
}

基于 MIT 许可发布