@monstermann/fn
Version:
A utility library for TypeScript.
56 lines • 1.75 kB
TypeScript
//#region src/promise/debounce.d.ts
interface Debounced<T extends unknown[]> {
(...args: T): void;
clear: () => void;
flush: () => void;
idle: (gracePeriod?: number) => Promise<void>;
isIdle: () => boolean;
isPending: () => boolean;
isRunning: () => boolean;
}
type DebounceOptions = {
leading?: boolean;
maxWait?: number;
trailing?: boolean;
wait: number;
};
/**
* `debounce(fn, options)`
*
* Creates a debounced function that delays invoking `fn` until after `options.wait` milliseconds have elapsed since the last time the debounced function was invoked.
*
* Implementation details:
*
* - Only one `fn` can run at any given time, asynchronous functions can not conflict with each other
* - Pending calls are not accumulated in an internal array and asynchronously resolved
*
* ```ts
* const debouncedSave = debounce(saveData, {
* wait: 1000,
* // Maximum time to wait after the first call, default: undefined
* maxWait?: 5000,
* // Invoke function on the leading edge, default: false
* leading?: false,
* // Invoke function on the trailing edge, default: true
* trailing?: true,
* });
*
* // void
* debouncedSave(data);
*
* // Cancel pending execution - does not cancel current invocation
* debouncedSave.clear();
*
* // Execute pending invocation asap
* debouncedSave.flush();
*
* debouncedSave.isIdle();
* debouncedSave.isPending();
* debouncedSave.isRunning();
*
* // Wait until idle, if a `gracePeriod` is given then wait
* // until it has been idle for `gracePeriod` milliseconds
*/
declare function debounce<T extends unknown[]>(fn: (...args: T) => void | Promise<void>, options: DebounceOptions): Debounced<T>;
//#endregion
export { Debounced, debounce };