Skip to content

节流函数 (throttle)

创建一个节流函数,限制函数在指定时间内最多执行一次。常用于处理频繁触发的事件,如滚动、调整窗口大小等。

签名

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

参数

  • fn (Function): 需要节流的函数。
  • wait (number): 等待时间,单位毫秒。
  • options (Object): 可选的配置对象。
    • leading (boolean): 是否在延迟开始前调用,默认 true
    • trailing (boolean): 是否在延迟结束后调用,默认 true

返回值

(Function): 返回节流后的函数,该函数具有 cancel 方法用于取消延迟的函数调用。

示例

typescript
import { throttle } from '@fu/matrix';
// 或
const throttle = window.fuMatrix.throttle;

// 基本用法
const throttled = throttle(() => {
  console.log('scroll');
}, 1000);

window.addEventListener('scroll', throttled);

// 自定义选项
const throttledWithOptions = throttle(
  () => {
    console.log('resize');
  },
  1000,
  { leading: false }
);

window.addEventListener('resize', throttledWithOptions);

// 取消节流
throttled.cancel();

注意事项

  • 节流函数会在每个等待时间窗口内最多执行一次
  • leadingfalse 时,第一次调用会被延迟
  • trailingfalse 时,最后一次调用可能会被忽略
  • 调用 cancel() 方法可以取消当前的延迟执行