手写节流 throttle、防抖 debounce

77 阅读1分钟
// 节流就是【技能冷却】
const throttle = (fn, time) => {
  let 冷却中 = false
  return (...args) => {
    if(冷却中) return
    fn.call(undefined, ...args)
    冷却中 = true
    setTimeout(() => {
        冷却中 = false
    }, time)
  }
}
// 还有一个版本是在冷却结束时调用 fn

// 防抖就是【回城被打断】
const debounce = (fn, time) => {
  let 回城计时器 = null
  return (...args) => {
    if(回城计时器 !== null) {
      clearTimeout(回城计时器) // 打断回城
    }
    // 重新回城
    回城计时器 = setTimeout(() => {
      fn.call(undefined, ...args) // 回城后调用 fn
      回城计时器 = null
    }, time)
  }
}