Skip to content

函数防抖

**函数防抖(Debounce)**是一种前端性能优化技术,用来控制高频触发函数的执行时机。

一句话概括: 在事件被频繁触发时,只在“最后一次触发后的指定时间”才执行函数。

为什么需要防抖

有些事件触发频率非常高,比如:

  • input / keyup(输入框实时输入)
  • resize(窗口缩放)
  • scroll(滚动)
  • 搜索框联想查询

如果每次触发都执行逻辑,会导致:

  • 性能浪费
  • 接口频繁请求
  • 页面卡顿

防抖的目的:等用户“停下来”再执行

防抖实现

基础实现:

ts
function debounce(fn, delay) {
  let timer = null

  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

使用函数防抖:

ts
const onInput = debounce(() => {
  console.log('发送请求')
}, 500)

input.addEventListener('input', onInput)