这里提供两种方式实现为函数添加节流功能的函数:

方法一:使用setTimeout延迟执行函数

function throttle(fn, delay) {
  let timerId = null;
  return function() {
    const context = this;
    const args = arguments;
    if (!timerId) {
      timerId = setTimeout(function() {
        fn.apply(context, args);
        timerId = null;
      }, delay);
    }
  };
}

使用示例:

function myFunction() {
  console.log('执行了 myFunction');
}

const throttledFunction = throttle(myFunction, 1000);

throttledFunction(); // 在 1000ms 后执行 myFunction
throttledFunction(); // 不会立即执行 myFunction
throttledFunction(); // 不会立即执行 myFunction

方法二:使用时间戳判断是否执行函数

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

使用示例:

function myFunction() {
  console.log('执行了 myFunction');
}

const throttledFunction = throttle(myFunction, 1000);

throttledFunction(); // 立即执行 myFunction
throttledFunction(); // 在 1000ms 后执行 myFunction
throttledFunction(); // 在 1000ms 后执行 myFunction
``
ts写一个为函数添加节流功能的函数

原文地址: https://www.cveoy.top/t/topic/cQ5l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录