防抖 debounce 和 节流 throttle 的区别?

防抖(debounce)和节流(throttle)都是前端开发中用于优化频繁触发事件(如 scrollresizeinputmousemove 等)的方法,但它们的应用场景和实现思路所有不同。

一句话总结:

  • 防抖:最后一次触发后等待一段时间再执行(拖后执行
  • 节流:每隔一段时间执行一次(间隔执行
特性 防抖(Debounce) 节流(Throttle)
定义 事件被触发后延迟一段时间执行,若期间再次触发则重新计时 一定时间间隔内只执行一次
触发频率 停止触发一段时间后才执行一次 每隔固定时间执行一次
常见场景 搜索框输入、按钮点击防止重复提交等 页面滚动监听、窗口 resize、拖拽等
实现原理 setTimeout + 清除旧定时器 setTimeout 或 时间戳比较
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

使用场景示例:

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

inputElement.addEventListener('input', onInput);
function throttle(fn, delay) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
}

使用场景示例:

const onScroll = throttle(() => {
  console.log('处理滚动事件');
}, 200);

window.addEventListener('scroll', onScroll);