Skip to content

throttle

throttle<T>(fn, wait?, options?): (...args: Parameters<T>) => undefined | ReturnType<T>

节流函数

创建一个节流函数,限制函数在给定的时间窗口内最多执行一次

Type parameters

NameType
Textends (...args: unknown[]) => unknown

Parameters

NameTypeDefault valueDescription
fnTundefined-
waitnumber200时间窗口的毫秒数,默认为 200ms
optionsObject{}-
options.leading?booleanundefined-
options.trailing?booleanundefined-

Returns

fn

节流后的函数

(...args): undefined | ReturnType<T>

Parameters
NameType
...argsParameters<T>
Returns

undefined | ReturnType<T>

NameType
cancel() => void

Example

ts
// 基本用法
const throttledScroll = throttle(() => {
  console.log('Scroll event handled');
}, 300);

// 添加到滚动事件
window.addEventListener('scroll', throttledScroll);

// 即使快速滚动,每 300ms 最多执行一次

Released under the MIT License.