JS如何实现节流 throttle、防抖 debounce?

134 阅读1分钟

最近在复习js的基础知识,看到有一个关于JS如何实现节流 throttle、防抖 debounce的题目,很经典的一道题,记录一下。

防抖原理(思路):事件触发,延迟一定的时间再做处理,如果在等待的时间内事件又触发,上次处理已经没有意义故此可以消除,继续处理新的内容。

debounce(防抖)和 throttle(节流)是一种编程技巧,用于控制某个函数在一定时间内执行多少次。主要用于平滑事件响应、减轻浏览器压力。

节流:

// 节流就是「技能冷却中」
const throttle = (fn, time) => {
  let 冷却中 = false
  return (...args) => {
    if(冷却中) return
    fn.call(undefined, ...args)
    冷却中 = true
    setTimeout(()=>{
      冷却中 = false
    }, time)
  }
}
// 还有一个版本是在冷却结束时调用 fn
// 简洁版,删掉冷却中变量,直接使用 timer 代替
const throttle = (f, time) => {
  let timer = null
  return (...args) => {
		if(timer) {return}
		f.call(undefined, ...args)
		timer = setTimeout(()=>{
		  timer = null
		}, time)
  }
}

使用方法:

const f = throttle(()=>{console.log('hi')}, 3000)

f() // 打印 hi
f() // 技能冷却中

节流:无论事件触发有多快,都会每隔时间内处理一次

防抖:

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