框架
版本
防抖器 API 参考
节流器 API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考

节流

函数:throttle()

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

定义于:throttler.ts:355

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

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

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

要处理事件爆发,请考虑使用 debounce()。要进行硬执行限制,请考虑使用 rateLimit()。

状态管理

  • 使用 TanStack Store 进行响应式状态管理
  • 使用 initialState 在创建节流器时提供初始状态值
  • 使用 onExecute 回调来响应函数执行并实现自定义逻辑
  • 状态包括执行次数、上次执行时间、挂起状态等
  • 可以通过底层 Throttler 实例的 store.state 属性访问状态
  • 在使用框架适配器(React/Solid)时,状态从 hook 的 state 属性访问

类型参数

TFn extends AnyFunction

参数

fn

TFn

initialOptions

ThrottlerOptions<TFn>

Returns (返回)

Function

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

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

    • 当 leading=true 时:立即执行
    • 当 leading=false 时:等待下一次尾部执行
  • 在等待周期内

    • 当 trailing=true 时:安排在等待周期结束时执行
    • 当 trailing=false 时:丢弃执行

参数

args

...Parameters<TFn>

Returns (返回)

void

示例

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

// First call executes immediately
throttled.maybeExecute('a', 'b');

// Call during wait period - gets throttled
throttled.maybeExecute('c', 'd');
const throttled = new Throttler(fn, { wait: 1000 });

// First call executes immediately
throttled.maybeExecute('a', 'b');

// Call during wait period - gets throttled
throttled.maybeExecute('c', 'd');

示例

ts
// Basic throttling - max once per second
const throttled = throttle(updateUI, { wait: 1000 });

// Configure leading/trailing execution
const throttled = throttle(saveData, {
  wait: 2000,
  leading: true,  // Execute immediately on first call
  trailing: true  // Execute again after delay if called during wait
});
// Basic throttling - max once per second
const throttled = throttle(updateUI, { wait: 1000 });

// Configure leading/trailing execution
const throttled = throttle(saveData, {
  wait: 2000,
  leading: true,  // Execute immediately on first call
  trailing: true  // Execute again after delay if called during wait
});
我们的合作伙伴
Code Rabbit
Unkey
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。