防抖节流

68 阅读2分钟

前端 JavaScript 中的防抖和节流是两种常用的优化技术,可以有效地减少函数执行次数,提高性能。下面将详细介绍它们的实现方法。

一、防抖 (debounce)

防抖是一种优化技术,它通过延迟执行某个操作,来减少该操作的执行次数。在前端 JavaScript 中,防抖常用于输入框实时搜索等功能。

实现方法:

function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

在上述代码中,debounce 函数接收两个参数:func 需要进行防抖的函数,wait 延迟执行的时间。在返回的函数中,通过清除之前的定时器,并重新设置定时器来延迟执行 func 函数。

使用示例:

const searchDebounced = debounce(function() {
  console.log(this.value); // 处理输入框实时搜索
}, 300);
// 在输入框事件中调用 searchDebounced 函数
inputElement.addEventListener('input', searchDebounced);

在这个示例中,通过防抖将 console.log 函数的执行延迟了 300 毫秒,减少了实时搜索的次数。

二、节流 (throttle)

节流是一种优化技术,它通过限制函数的执行频率,来减少函数执行次数。在前端 JavaScript 中,节流常用于滚动加载、窗口大小调整等功能。

实现方法:

function throttle(func, limit) {
  let inThrottle;
  return function() {
    const context = this;
    const args = arguments;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

在上述代码中,throttle 函数同样接收两个参数:func 需要进行节流的函数,limit 执行的时间间隔。在返回的函数中,通过设置一个定时器来限制 func 函数的执行频率。

使用示例:

const scrollThrottled = throttle(function() {
  console.log(window.scrollY); // 处理滚动加载
}, 200);
window.addEventListener('scroll', scrollThrottled);

在这个示例中,通过节流将 console.log 函数的执行限制为每 200 毫秒一次,减少了滚动加载的次数。