Skip to main content
All playgrounds

Debouncing

1. What is debouncing?

Debouncing is a technique that delays the execution of a function until a specified period of time has passed since it was last invoked. If the function is called again before that period ends, the pending call is discarded and the timer resets.

A rapid series of calls produces a single execution, using the arguments of the most recent call. Intermediate calls are dropped, not queued, and if the calls never pause for the full wait, the function never runs.

The timeoutID lives in a closure, so every call shares it: clear the old timer, then start a new one.

debounce.ts
export default function debounce(func: Function, wait: number): Function {
let timeoutID: ReturnType<typeof setTimeout> | null = null;

return function (this: any, ...args: any[]) {
const context = this;
clearTimeout(timeoutID ?? undefined);
timeoutID = setTimeout(function () {
timeoutID = null;
func.apply(context, args);
}, wait);
};
}

2. What if it should run immediately?

Use a leading-edge debounce: the function runs on the first call, and every call after it is ignored until no call has happened for the full wait.

The timer no longer schedules the function. It only marks the burst as busy: if no timer is running, the call is the first one and runs immediately.

Trade-off: it reacts instantly but uses the first value, not the last. Good for submit buttons, bad for search boxes.

debounceLeading.ts
export default function debounceLeading(func: Function, wait: number): Function {
let timeoutID: ReturnType<typeof setTimeout> | null = null;

return function (this: any, ...args: any[]) {
const context = this;
if (timeoutID === null) {
func.apply(context, args);
}
clearTimeout(timeoutID ?? undefined);
timeoutID = setTimeout(function () {
timeoutID = null;
}, wait);
};
}

Try it: click Place order rapidly. Only the first click of each burst runs; edit WAIT to see the window change.

Loading editor...