以下是一个为函数添加节流功能的 TypeScript 函数:

type ThrottleFunction<T extends (...args: any[]) => any> = (func: T, delay: number) => T;

const throttle: ThrottleFunction<(...args: any[]) => any> = (func, delay) => {
  let timeoutId: ReturnType<typeof setTimeout> | null = null;
  let lastExecutedTime = 0;

  const throttledFunc = (...args: Parameters<typeof func>) => {
    const currentTime = Date.now();

    if (!lastExecutedTime || currentTime - lastExecutedTime >= delay) {
      lastExecutedTime = currentTime;
      func(...args);
    } else if (timeoutId === null) { // only schedule a new timeout if there isn't one already
      timeoutId = setTimeout(() => {
        lastExecutedTime = Date.now();
        func(...args);
        timeoutId = null;
      }, delay - (currentTime - lastExecutedTime));
    }
  };

  return throttledFunc as T;
};

该函数接受一个函数和一个延迟时间作为参数,并返回一个具有节流功能的新函数。新函数将在调用时执行指定的函数,但在延迟时间内重复调用将被忽略。如果在延迟时间内有多个调用,则只有最后一个调用会在延迟时间结束后执行。

例如,以下代码将使用 throttle 函数来创建具有节流功能的 scrollHandler 函数:

const scrollHandler = () => {
  console.log('scroll event');
};

const throttledScrollHandler = throttle(scrollHandler, 1000);

window.addEventListener('scroll', throttledScrollHandler);
``
ts写一个为函数添加节流功能的函数要有类型

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

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