JavaScript

JavaScript防抖与节流有哪些实现方法

小樊
82
2024-10-25 22:19:29
栏目: 编程语言

在 JavaScript 中,防抖(debounce)和节流(throttle)是两种常用的优化高频率触发事件的技术。它们都可以用来控制函数的执行频率,从而提高性能。以下是它们的实现方法:

防抖(debounce)

防抖的基本思想是:在事件被触发后 n 秒内函数只能执行一次,如果在这 n 秒内又被重新触发,则重新计时。

实现方法 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);
  };
}

节流(throttle)

节流的基本思想是:预先设定一个执行周期,周期内只执行一次函数。

实现方法 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 中防抖和节流的实现方法。在实际项目中,可以根据具体需求选择合适的实现方式。

0
看了该问题的人还看了