其他分享
首页 > 其他分享> > 手写防抖函数debounce和节流函数throttle

手写防抖函数debounce和节流函数throttle

作者:互联网

防抖 debounce

function debounce(fn, delay, immedia = false) {
  let timer = null
  return () => {
    if (timer) clearTimeout(timer)
    // 首次立即执行
    if (immedia && !timer) {
      fn.call(this)
      timer = setTimeout(() => {
        timer = null
      }, delay)
    }
    timer = setTimeout(() => {
      fn.call(this)
      timer = null
    }, delay)
  }
}

限流 throttle。

function throttle() {
  let previous = 0
  return () => {
    const now = Date.now()
    if (now - previous > delay) {
      fn.call(this)
      previous = Date.now()
    }
  }
}

标签:防抖,null,throttle,函数,timer,delay,call,now,fn
来源: https://www.cnblogs.com/gesheng/p/15604033.html