@tienedev/datype
Version:
Modern TypeScript utility library with pragmatic typing and zero dependencies
84 lines • 2.91 kB
TypeScript
/**
* Options for configuring debounce behavior
*/
export interface DebounceOptions {
/**
* If true, the function is called on the leading edge of the timeout.
* @default false
*/
leading?: boolean;
/**
* If true, the function is called on the trailing edge of the timeout.
* @default true
*/
trailing?: boolean;
/**
* Maximum time the function can be delayed before it's invoked.
* If specified, the function will be called at most once per `maxWait` milliseconds.
*/
maxWait?: number;
}
/**
* Debounced function interface with additional control methods
*/
export interface DebouncedFunction<TArgs extends readonly unknown[], TReturn> {
/**
* Call the debounced function
*/
(...args: TArgs): TReturn | undefined;
/**
* Cancel any pending execution
*/
cancel(): void;
/**
* Immediately execute the function with the last provided arguments
*/
flush(): TReturn | undefined;
/**
* Check if there's a pending execution
*/
pending(): boolean;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time the debounced function was invoked.
*
* @template TArgs - The argument types of the function
* @template TReturn - The return type of the function
* @param func - The function to debounce
* @param wait - The number of milliseconds to delay
* @param options - Options object to configure debounce behavior
* @returns A new debounced function with cancel, flush, and pending methods
*
* @example
* ```typescript
* import { debounce } from 'datype';
*
* // Basic debouncing - delays execution until 300ms after last call
* const debouncedSearch = debounce((query: string) => {
* console.log('Searching for:', query);
* return fetchSearchResults(query);
* }, 300);
*
* // Only the last call will execute after 300ms
* debouncedSearch('a');
* debouncedSearch('ab');
* debouncedSearch('abc'); // Only this will execute
*
* // Leading edge execution - executes immediately on first call
* const leadingDebounce = debounce(() => {
* console.log('Button clicked!');
* }, 1000, { leading: true, trailing: false });
*
* // Control methods
* const debounced = debounce(() => console.log('Hello'), 1000);
* debounced.cancel(); // Cancel pending execution
* debounced.flush(); // Execute immediately
* debounced.pending(); // Check if execution is pending
*
* // Maximum wait time - ensures function is called at most once per maxWait
* const maxWaitDebounce = debounce(updateUI, 100, { maxWait: 1000 });
* ```
*/
export declare function debounce<TArgs extends readonly unknown[], TReturn>(func: (...args: TArgs) => TReturn, wait: number, options?: DebounceOptions): DebouncedFunction<TArgs, TReturn>;
//# sourceMappingURL=index.d.ts.map