防抖与节流

防抖(Debounce)和节流(Throttle)是前端开发中常用的一种技术,主要用于优化性能和提升用户体验。

防抖(Debounce)

理解:在事件被触发 n 秒后再执行回调,如果在这 n 秒内事件又被触发,则重新计时。

实现:通过设置定时器实现。当事件触发时,定时器到达指定时间后执行操作。如果在定时器到达之前再次触发事件,则清除之前的定时器并重新设置一个新的定时器,然后重新计时。‌

应用场景:输入框搜索、窗口大小调整、按钮点击、滚动条滚动等。

// 定义防抖函数
function debounce(fn, delay) {
  let timer = null
  return function () {
    const _self = this
    const args = arguments
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(_self, args)
    }, delay)
  }
}

// html部分
<input type="text" id="inp" placeholder="请输入搜索" />

// 使用防抖函数
const inp = document.getElementById('inp')
inp.oninput = debounce(onInputChange, 1000) // 输入框输入时,1秒后执行onInputChange函数
function onInputChange(e) {
  console.log(e.target.value)
}

节流(Throttle)

理解:规定在一个单位时间 n 内,只能触发一次函数。如果这个单位时间 n 内触发多次函数,只有一次生效。

实现:可以通过定时器实现。首次触发时设置定时器,定时器到达时间后执行操作,而且定时器清空。如果在定时器到达前再次触发事件,则无视此次触发事件。‌

应用场景:拖拽、鼠标移动、表单验证等

// 节流函数
function throttle(fn, delay) {
  let timer = null
  return function () {
    const _self = this
    const args = arguments
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(_self, args)
      timer = null
    }, delay)
  }
}

// html部分
<input type="submit" value="提交" onclick="onSubmit(event)" /

// 使用节流函数
function submitEvent(e) {
  console.log(e.target.value)
}
const onSubmit = throttle(submitEvent, 1000) // 点击提交按钮,1秒内只能提交一次

从上面的代码可以看出,防抖与节流都是基于闭包来实现的

posted @ 2025-03-04 21:55  老甄Home  阅读(30)  评论(0)    收藏  举报