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

Throttler

类:Throttler<TFn>

定义于:throttler.ts:71

一个创建节流函数的类。

节流确保函数在指定的时间窗口内最多调用一次。 与等待调用暂停的防抖不同,节流无论调用频率如何,都能保证一致的执行时序。

支持前沿和后沿执行:

  • 前沿:首次调用时立即执行(默认值:true)
  • 后沿:如果在节流期间调用,则在等待期后执行(默认值:true)

对于只关心最后一次调用的快速连续事件的折叠,请考虑使用 Debouncer。

示例

ts
const throttler = new Throttler(
  (id: string) => api.getData(id),
  { wait: 1000 } // 每秒最多执行一次
);

// 首次调用立即执行
throttler.maybeExecute('123');

// 1000 毫秒内的后续调用将被节流
throttler.maybeExecute('123'); // 已节流
const throttler = new Throttler(
  (id: string) => api.getData(id),
  { wait: 1000 } // 每秒最多执行一次
);

// 首次调用立即执行
throttler.maybeExecute('123');

// 1000 毫秒内的后续调用将被节流
throttler.maybeExecute('123'); // 已节流

类型参数

TFn extends AnyFunction

构造函数

new Throttler()

ts
new Throttler<TFn>(fn, initialOptions): Throttler<TFn>
new Throttler<TFn>(fn, initialOptions): Throttler<TFn>

定义于:throttler.ts:78

参数

fn

TFn

initialOptions

ThrottlerOptions<TFn>

返回

Throttler<TFn>

方法

cancel()

ts
cancel(): void
cancel(): void

定义于:throttler.ts:189

取消任何待处理的后沿执行并清除内部状态。

如果已计划后沿执行(由于使用 trailing=true 进行节流), 这将阻止该执行发生。内部超时和存储的参数将被清除。

如果没有待处理的执行,则无效。

返回

void


getEnabled()

ts
getEnabled(): boolean
getEnabled(): boolean

定义于:throttler.ts:110

返回节流器的当前启用状态

返回

boolean


getExecutionCount()

ts
getExecutionCount(): number
getExecutionCount(): number

定义于:throttler.ts:214

返回函数已执行的次数

返回

number


getIsPending()

ts
getIsPending(): boolean
getIsPending(): boolean

定义于:throttler.ts:221

如果存在待处理的执行,则返回 true

返回

boolean


getLastExecutionTime()

ts
getLastExecutionTime(): number
getLastExecutionTime(): number

定义于:throttler.ts:200

返回上次执行时间

返回

number


getNextExecutionTime()

ts
getNextExecutionTime(): number
getNextExecutionTime(): number

定义于:throttler.ts:207

返回下次执行时间

返回

number


getOptions()

ts
getOptions(): Required<ThrottlerOptions<TFn>>
getOptions(): Required<ThrottlerOptions<TFn>>

定义于:throttler.ts:103

返回当前节流器选项

返回

Required<ThrottlerOptions<TFn>>


getWait()

ts
getWait(): number
getWait(): number

定义于:throttler.ts:117

返回当前等待时间(以毫秒为单位)

返回

number


maybeExecute()

ts
maybeExecute(...args): void
maybeExecute(...args): void

定义于:throttler.ts:143

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

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

    • 使用 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');

setOptions()

ts
setOptions(newOptions): void
setOptions(newOptions): void

定义于:throttler.ts:91

更新节流器选项

参数

newOptions

Partial<ThrottlerOptions<TFn>>

返回

void