The function to debounce.
Milliseconds to delay subsequent invocations.
Debounced function with immediate leading call.
export function debounceImmediate<T extends (...args: unknown[]) => unknown>(
func: T,
wait: number,
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let isFirstCall = true;
return function debouncedImmediate(...args: Parameters<T>): void {
if (isFirstCall) {
func(...args);
isFirstCall = false;
}
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func(...args);
timeoutId = null;
isFirstCall = true;
}, wait);
};
}
Creates a debounced function that immediately invokes on the leading edge and delays subsequent calls. Useful for operations that should happen immediately but also batch follow-up calls.