debounce函数(消抖函数)

Source Code:

/**
 * 消抖函数
 * @param {Function} fn    原始函数
 * @param {Number}   delay 延迟执行时间
 * @param {Number}   wait  最小执行间隔
 */
const debounce = (fn, delay, wait = 0) => {
  let timeID = 0
  let waitTimerID = 0
  let args
  return (...rest) => {
    args = rest
    clearTimeout(timeID)
    timeID = setTimeout(() => {
      clearTimeout(waitTimerID)
      waitTimerID = 0
      fn.apply(null, args)
    }, delay)
    if (!waitTimerID && wait > 0) {
      waitTimerID = setTimeout(() => {
        clearTimeout(timeID)
        waitTimerID = 0
        fn.apply(null, args)
      }, wait)
    }
  }
}

Example:

function func(n) {
  console.log(n)
}
let debouncedFunc = debounce(func, 100, 500)

debouncedFunc(100)