实现防抖与节流函数

93 阅读1分钟

防抖、节流的意义

在一些高频率事件触发的场景下,我们希望对应的事件只执行一次

防抖、节流适用的场景

  1. 点击事件
  2. 滚动事件
  3. 轮播事件
  4. input模糊匹配

防抖函数的实现

const debounce = (fn, wait) => {
  if(typeof fn !== 'function') throw new Error('fn must function')
  if(typeof wait === 'undefined') wait = 1000
  let timer = null
  
  return function proxy(...args) {
    const that = this
    clearTimeout(timer)
    
    timer = setTimeout(() => {
      fn.call(that,args)
    }, wait)
  }
}

节流函数的实现

const throttle = (fn,wait) => {
  if(typeof fn !== 'function') throw new Error('fn must function')
  if(typeof wait === 'undefined') wait = 1000
  let previous = 0 // 记录上一次执行的时间
  let timer = null
  
  return function proxy(...args) {
    const that = this
    const now = new Date()
    const interval = wait - now + previous
    
    if(interval <= 0) {
      // 非高频操作
      clearTimeout(timer)
      timer = null
      fn.call(that, ...args)
      previous = new Date()
    } else if(!timer) {
      timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
        fn.call(that, ...args)
        previous = new Data()
      }, interval)
    }
  }
}