实现防抖和节流

手写防抖和节流函数

问题

实现 debounce(防抖)和 throttle(节流)函数。

解答

防抖(Debounce)

延迟执行,直到一段不活动期后才执行。

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

// 使用
const handleSearch = debounce((query) => {
  console.log('搜索:', query);
}, 300);

节流(Throttle)

限制执行频率,在指定时间段内最多执行一次。

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

// 使用
const handleScroll = throttle(() => {
  console.log('滚动事件');
}, 100);

使用场景

  • 防抖:搜索输入、表单验证、窗口调整大小
  • 节流:滚动事件、鼠标移动、API 限流