debounce

Limit function execution rate by delaying until calls stop.

#async #performance #events #utility
export const debounce = <T extends (...args: unknown[]) => void>(
fn: T,
delay = 300,
) => {
let id: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), delay);
};
};
// Usage
const debouncedSearch = debounce((query: string) => {
console.log('Searching:', query);
}, 300);
input.addEventListener('input', (e) => {
debouncedSearch((e.target as HTMLInputElement).value);
});

Share this snippet

Comments