返回

Debounce 和 Throttle:函数调用控制技术解析及实例比较

前端

Debounce

Debounce 技术会在一段时间内只执行一次函数。如果在规定的时间内函数被多次调用,只有最后一次调用会被执行。

代码示例

function debounce(func, wait, immediate) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    const later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

Throttle

Throttle 技术会在一段时间内只执行一次函数。如果在规定的时间内函数被多次调用,只有第一次调用会被执行。

代码示例

function throttle(func, wait, options) {
  let timeout;
  let previous = 0;
  const opts = options || {};
  const leading = opts.leading || false;
  const trailing = opts.trailing || true;
  return function() {
    const now = Date.now();
    const remaining = wait - (now - previous);
    const context = this;
    const args = arguments;
    if (leading && !timeout) {
      func.apply(context, args);
      previous = now;
    }
    else if (trailing) {
      clearTimeout(timeout);
      timeout = setTimeout(function() {
        timeout = null;
        func.apply(context, args);
        previous = now;
      }, remaining);
    }
  };
}

区别

Debounce 和 Throttle 的主要区别在于:

  • Debounce 会在一段时间内只执行一次函数,只有最后一次调用会被执行。
  • Throttle 会在一段时间内只执行一次函数,只有第一次调用会被执行。

应用场景

Debounce 和 Throttle 都可以用于控制函数的调用频率,从而提高应用程序的性能。

  • Debounce 可以用于防止函数在短时间内被重复调用,例如:

    • 表单验证:在用户输入时,表单验证函数只会被执行一次。
    • 搜索框自动补全:在用户输入时,搜索框自动补全功能只会被执行一次。
  • Throttle 可以用于防止函数在短时间内被重复调用,例如:

    • 窗口滚动事件:在用户滚动窗口时,窗口滚动事件只会被执行一次。
    • 鼠标移动事件:在用户移动鼠标时,鼠标移动事件只会被执行一次。

选择

在选择 Debounce 和 Throttle 时,需要考虑以下因素:

  • 函数是否需要在短时间内多次执行:如果函数需要在短时间内多次执行,则应该使用 Debounce。
  • 函数是否需要在一段时间内只执行一次:如果函数需要在一段时间内只执行一次,则应该使用 Throttle。

总结

Debounce 和 Throttle 都是两个用于控制函数调用频率的技术,它们可以防止函数在短时间内被重复调用,从而提高应用程序的性能。在选择 Debounce 和 Throttle 时,需要考虑函数是否需要在短时间内多次执行、是否需要在一段时间内只执行一次等因素。