溫馨提示×

JavaScript防抖與節(jié)流有哪些實現方法

小樊
81
2024-10-25 22:19:29
欄目: 編程語言

在 JavaScript 中,防抖(debounce)和節(jié)流(throttle)是兩種常用的優(yōu)化高頻率觸發(fā)事件的技術。它們都可以用來控制函數的執(zhí)行頻率,從而提高性能。以下是它們的實現方法:

防抖(debounce)

防抖的基本思想是:在事件被觸發(fā)后 n 秒內函數只能執(zhí)行一次,如果在這 n 秒內又被重新觸發(fā),則重新計時。

實現方法 1:遞歸實現

function debounce(func, wait) {
  let timeout;

  return function (...args) {
    const context = this;

    clearTimeout(timeout);

    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

實現方法 2:使用閉包

function debounce(func, wait) {
  let timeout;

  return function (...args) {
    const context = this;

    const later = function () {
      timeout = null;
      func.apply(context, args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

節(jié)流(throttle)

節(jié)流的基本思想是:預先設定一個執(zhí)行周期,周期內只執(zhí)行一次函數。

實現方法 1:使用閉包

function throttle(func, limit) {
  let inThrottle;

  return function (...args) {
    const context = this;

    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

實現方法 2:使用 ES6 的 Promiseasync/await

function throttle(func, limit) {
  let canRun = true;

  return async function (...args) {
    const context = this;

    if (!canRun) return;

    canRun = false;
    await func.apply(context, args);
    setTimeout(() => {
      canRun = true;
    }, limit);
  };
}

以上就是 JavaScript 中防抖和節(jié)流的實現方法。在實際項目中,可以根據具體需求選擇合適的實現方式。

0