Skip to content

throttle() function

throttle 函数创建一个节流版本的函数,该函数在指定的时间段内最多只能被调用一次。与 debounce 不同,throttle 确保在连续调用期间函数以规律的间隔被调用,而不是等待暂停。这对于限制诸如滚动处理程序、窗口调整大小或 API 调用等昂贵操作的频率非常有用。

节流函数支持 leadingtrailing 边缘执行:

  • leading: 在第一次调用时立即执行
  • trailing: 在节流周期结束时使用最新参数执行

节流函数包含一个 .cancel() 方法来取消待处理的 trailing 调用。

Signature:

typescript
declare function throttle<T extends (...args: any[]) => void>(
  func: T,
  wait: number,
  options?: {
    leading: boolean;
    trailing: boolean;
  },
): ((...args: Parameters<T>) => void) & {
  cancel: () => void;
};

Example

ts
// 基本用法(默认选项 - leading 和 trailing 都启用)
const throttled = throttle((val: number) => {
  console.log("val", val);
}, 1000);

throttled(1); // 立即输出: val 1
throttled(2); // 被忽略
throttled(3); // 被忽略
// 1000ms 后输出: val 3 (使用最新参数的 trailing 调用)
ts
// 仅 Leading 边缘(用于防止快速重复操作)
const throttled = throttle(
  (val: number) => {
    console.log("val", val);
  },
  1000,
  { leading: true, trailing: false },
);

throttled(1); // 立即输出: val 1
throttled(2); // 被忽略
throttled(3); // 被忽略
// 1000ms 后什么也不发生
ts
// 仅 Trailing 边缘(用于批处理)
const throttled = throttle(
  (val: number) => {
    console.log("val", val);
  },
  1000,
  { leading: false, trailing: true },
);

throttled(1); // 延迟
throttled(2); // 延迟
throttled(3); // 延迟
// 1000ms 后输出: val 3 (仅最新值)
ts
// 取消待处理的节流调用
const throttled = throttle((val: number) => {
  console.log("val", val);
}, 1000);

throttled(1); // 立即输出: val 1
throttled(2);
throttled(3);
throttled.cancel(); // 取消待处理的 trailing 调用
// 1000ms 后什么也不发生
ts
// 实际使用案例 - 节流滚动事件
const handleScroll = throttle(() => {
  console.log("Scroll position:", window.scrollY);
}, 200);

window.addEventListener("scroll", handleScroll);

// 处理程序将在第一次滚动时立即触发,
// 在连续滚动期间每200ms最多触发一次,
// 并在滚动停止后再触发一次(trailing 边缘)

Open Source Code

Released under the Apache-2.0 License.