框架
版本
Debouncer API 参考
Throttler API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考
批处理器示例

throttle

函数:throttle()

ts
function throttle<TFn>(fn, initialOptions): (...args) => void
function throttle<TFn>(fn, initialOptions): (...args) => void

定义于:throttler.ts:252

创建一个节流函数,该函数限制所提供函数的执行频率。

节流确保函数在指定的时间窗口内最多执行一次, 无论它被调用多少次。这对于限制昂贵的操作或 UI 更新的速率非常有用。

可以将节流函数配置为通过选项在节流窗口的前沿和/或后沿执行。

对于处理突发事件,请考虑改用 debounce()。对于硬执行限制,请考虑改用 rateLimit()。

类型参数

TFn extends AnyFunction

参数

fn

TFn

initialOptions

ThrottlerOptions<TFn>

返回

Function

尝试执行节流函数。执行行为取决于节流器选项:

  • 如果自上次执行以来已过足够的时间(>= 等待期):

    • 使用 leading=true:立即执行
    • 使用 leading=false:等待下一次后沿执行
  • 如果在等待期内:

    • 使用 trailing=true:计划在等待期结束时执行
    • 使用 trailing=false:丢弃执行

参数

args

...Parameters<TFn>

返回

void

示例

ts
const throttled = new Throttler(fn, { wait: 1000 });

// 首次调用立即执行
throttled.maybeExecute('a', 'b');

// 等待期内的调用 - 被节流
throttled.maybeExecute('c', 'd');
const throttled = new Throttler(fn, { wait: 1000 });

// 首次调用立即执行
throttled.maybeExecute('a', 'b');

// 等待期内的调用 - 被节流
throttled.maybeExecute('c', 'd');

示例

ts
// 基本节流 - 每秒最多一次
const throttled = throttle(updateUI, { wait: 1000 });

// 配置前沿/后沿执行
const throttled = throttle(saveData, {
  wait: 2000,
  leading: true,  // 首次调用时立即执行
  trailing: true  // 如果在等待期间调用,则在延迟后再次执行
});
// 基本节流 - 每秒最多一次
const throttled = throttle(updateUI, { wait: 1000 });

// 配置前沿/后沿执行
const throttled = throttle(saveData, {
  wait: 2000,
  leading: true,  // 首次调用时立即执行
  trailing: true  // 如果在等待期间调用,则在延迟后再次执行
});