throttle
throttle<T>(fn, wait?, options?): (...args: Parameters<T>) => undefined | ReturnType<T>
节流函数
创建一个节流函数,限制函数在给定的时间窗口内最多执行一次
Type parameters
| Name | Type |
|---|---|
T | extends (...args: unknown[]) => unknown |
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
fn | T | undefined | - |
wait | number | 200 | 时间窗口的毫秒数,默认为 200ms |
options | Object | {} | - |
options.leading? | boolean | undefined | - |
options.trailing? | boolean | undefined | - |
Returns
fn
节流后的函数
(...args): undefined | ReturnType<T>
Parameters
| Name | Type |
|---|---|
...args | Parameters<T> |
Returns
undefined | ReturnType<T>
| Name | Type |
|---|---|
cancel | () => void |
Example
ts
// 基本用法
const throttledScroll = throttle(() => {
console.log('Scroll event handled');
}, 300);
// 添加到滚动事件
window.addEventListener('scroll', throttledScroll);
// 即使快速滚动,每 300ms 最多执行一次