As asked
Implement a debounce function that delays invoking a callback until after a given wait period has elapsed since the last call. It should return a cancel method to clear any pending invocation.
Sample answer outline
Use a closure to hold the timeout handle. On each call, clear any existing timeout and set a new one. The cancel method calls clearTimeout. The candidate should handle the correct this context, optional leading-edge invocation, and explain why debounce is appropriate for search input vs throttle for scroll handlers.
Reference implementation (typescript)
function debounce<T extends (...args: unknown[]) => void>(
fn: T,
wait: number
): T & { cancel: () => void } {
let timer: ReturnType<typeof setTimeout> | undefined;
const debounced = (...args: Parameters<T>) => {
// TODO: implement
};
debounced.cancel = () => { /* TODO */ };
return debounced as T & { cancel: () => void };
}Expect these follow-ups
- How would you make this debounce also support a leading option that fires immediately on the first call?