As asked
Write a generic debounce function in TypeScript that delays execution of a callback until a specified number of milliseconds have passed since the last call. It should return a function with the same signature as the input and a cancel method.
Sample answer outline
Should return a typed wrapper that clears and resets a timer on each call. The cancel method clears the pending timer. Strong answers add proper generic typing so the returned function infers parameter and return types from the input function, and mention that the return value is undefined if debounced (not yet fired).
Reference implementation (typescript)
function debounce<T extends (...args: unknown[]) => unknown>(
fn: T,
delay: number
): ((...args: Parameters<T>) => void) & { cancel: () => void } {
// implement here
}Expect these follow-ups
- How would you add a leading option so the first call fires immediately and trailing calls are debounced?
- How does this differ from throttle and when would you use each in a search input?