Skip to content
JavaScript·Intermediate·Coding·1 min read

Why should a debounce utility expose cancel and flush?

Short interview answer

Cancel prevents obsolete work when a component unmounts or input loses relevance. Flush immediately runs pending trailing work, useful before form submission or navigation. Without lifecycle controls, delayed callbacks can update stale UI.

Example

JavaScript
function debounce(fn, delay) {  let t, lastArgs;  const debounced = (...args) => {    lastArgs = args;    clearTimeout(t);    t = setTimeout(() => fn(...lastArgs), delay);  };  debounced.cancel = () => clearTimeout(t);  debounced.flush = () => { clearTimeout(t); if (lastArgs) fn(...lastArgs); };  return debounced;}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Debounce and throttle

Related questions