🔄

防抖,节流

💡
Notion Tip: This page documents processes product managers should follow to ship features at Acme Corp. Helpful for getting new employees up to speed.

防抖 debounce

在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。
const debounce = (fn, delay = 500) => {
  let timer = null
  return function() {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn()
      timer = null
    }, delay)
  }
}
 

节流 throttle

每隔一段时间,只执行一次函数。
const throttle = (fn, delay = 100) => {
    let timer = null
    return () => {
        if (timer) {
            return
        }
        timer = setTimeout(() => {
            fn()
            timer = null
        }, delay)
    }
}