| 1 | interface ThrottleOptions {
|
|---|
| 2 | /**
|
|---|
| 3 | * An optional AbortSignal to cancel the throttled function.
|
|---|
| 4 | */
|
|---|
| 5 | signal?: AbortSignal;
|
|---|
| 6 | /**
|
|---|
| 7 | * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
|
|---|
| 8 | * If `edges` includes "leading", the function will be invoked at the start of the delay period.
|
|---|
| 9 | * If `edges` includes "trailing", the function will be invoked at the end of the delay period.
|
|---|
| 10 | * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period.
|
|---|
| 11 | * @default ["leading", "trailing"]
|
|---|
| 12 | */
|
|---|
| 13 | edges?: Array<'leading' | 'trailing'>;
|
|---|
| 14 | }
|
|---|
| 15 | interface ThrottledFunction<F extends (...args: any[]) => void> {
|
|---|
| 16 | (...args: Parameters<F>): void;
|
|---|
| 17 | cancel: () => void;
|
|---|
| 18 | flush: () => void;
|
|---|
| 19 | }
|
|---|
| 20 | /**
|
|---|
| 21 | * Creates a throttled function that only invokes the provided function at most once
|
|---|
| 22 | * per every `throttleMs` milliseconds. Subsequent calls to the throttled function
|
|---|
| 23 | * within the wait time will not trigger the execution of the original function.
|
|---|
| 24 | *
|
|---|
| 25 | * @template F - The type of function.
|
|---|
| 26 | * @param {F} func - The function to throttle.
|
|---|
| 27 | * @param {number} throttleMs - The number of milliseconds to throttle executions to.
|
|---|
| 28 | * @returns {(...args: Parameters<F>) => void} A new throttled function that accepts the same parameters as the original function.
|
|---|
| 29 | *
|
|---|
| 30 | * @example
|
|---|
| 31 | * const throttledFunction = throttle(() => {
|
|---|
| 32 | * console.log('Function executed');
|
|---|
| 33 | * }, 1000);
|
|---|
| 34 | *
|
|---|
| 35 | * // Will log 'Function executed' immediately
|
|---|
| 36 | * throttledFunction();
|
|---|
| 37 | *
|
|---|
| 38 | * // Will not log anything as it is within the throttle time
|
|---|
| 39 | * throttledFunction();
|
|---|
| 40 | *
|
|---|
| 41 | * // After 1 second
|
|---|
| 42 | * setTimeout(() => {
|
|---|
| 43 | * throttledFunction(); // Will log 'Function executed'
|
|---|
| 44 | * }, 1000);
|
|---|
| 45 | */
|
|---|
| 46 | declare function throttle<F extends (...args: any[]) => void>(func: F, throttleMs: number, { signal, edges }?: ThrottleOptions): ThrottledFunction<F>;
|
|---|
| 47 |
|
|---|
| 48 | export { type ThrottleOptions, type ThrottledFunction, throttle };
|
|---|