@matthew.ngo/reform
Version:
A flexible and powerful React form management library with advanced validation, state observation, and multi-group support
28 lines (26 loc) • 899 B
text/typescript
/**
* Creates a debounced function that delays invoking the provided function
* until after the specified wait time has elapsed since the last time it was invoked.
* Properly handles async functions by unwrapping the Promise.
*
* @param func - The function to debounce (can be async)
* @param wait - The number of milliseconds to delay
* @returns A debounced version of the function
*/
export function debounce<T extends (...args: any[]) => Promise<any>>(
func: T,
wait: number
): (...args: Parameters<T>) => ReturnType<T> {
let timeout: NodeJS.Timeout | null = null;
return function(...args: Parameters<T>): ReturnType<T> {
return new Promise((resolve) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(async () => {
const result = await func(...args);
resolve(result);
}, wait);
}) as ReturnType<T>;
};
}