Description
The debounce
fn returns a new function that postpones its execution until after delay
milliseconds have passed
since the last time it was invoked. This is useful for optimizing performance by limiting how frequently a
high-rate event handler (e.g. resize, scroll, input) actually runs.
Code Byte
export function debounce<T extends (...args: any[]) => void>(
func: T,
delay: number = 300
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return function(this: any, ...args: Parameters<T>) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Use cases
- Search inputs: Wait until the user stops typing before triggering an API call.
- Window events: Throttle resize or scroll handlers to run at most once per delay period.
- Auto-save: Save form data only after the user pauses typing.
- Button clicks: Prevent double-submits by debouncing rapid click events.
Example Usage:
import { debounce } from './debounce.util';
// 1) Debounced resize handler
const onResize = debounce(() => {
console.log('Window width:', window.innerWidth);
}, 500);
window.addEventListener('resize', onResize);
// 2) Debounced search input
const input = document.getElementById('search') as HTMLInputElement;
input.addEventListener(
'input',
debounce((event: Event) => {
const query = (event.target as HTMLInputElement).value;
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(res => res.json())
.then(data => console.log(data));
}, 300)
);