Debounce in TypeScript, no library needed
Published November 12, 2026
Debouncing waits until calls stop for a moment, then runs once. Useful for search-as-you-type, resize handlers and autosave. This version keeps the argument types of the wrapped function. Note: the wrapped function's return value is discarded, and the last call wins.
typescript
```typescript
export function debounce<A extends unknown[]>(fn: (...args: A) => void, wait = 250) {
let timer: ReturnType<typeof setTimeout> | undefined;
return (...args: A) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
// Usage
const search = debounce((query: string) => {
console.log("searching for", query);
}, 300);
input.addEventListener("input", (e) => search((e.target as HTMLInputElement).value));
```Shown as text and never run on HUMAN API. Review code before using it.