Problem Statement
In complex applications, we need the ability to cancel pending debounced operations—for example, when a component unmounts or when the user navigates away. Implement a debounce function with a cancel capability.
Requirements
Implement a debounce(func, wait) function that returns a debounced function with:
- A
cancel()method that cancels any pending invocation - Standard debounce behavior (trailing edge)
- The cancel method should be safe to call multiple times
Example Usage
const saveToServer = (data) => {
console.log(`Saving: ${JSON.stringify(data)}`);
return fetch("/api/save", { method: "POST", body: JSON.stringify(data) });
};
const debouncedSave = debounce(saveToServer, 2000);
// User makes changes
debouncedSave({ content: "draft 1" });
debouncedSave({ content: "draft 2" });
// User navigates away before 2 seconds
debouncedSave.cancel();
// Nothing is saved - pending call was cancelled
// React useEffect cleanup example
useEffect(() => {
const debouncedHandler = debounce(handleResize, 150);
window.addEventListener("resize", debouncedHandler);
return () => {
debouncedHandler.cancel(); // Cleanup!
window.removeEventListener("resize", debouncedHandler);
};
}, []);Follow-up Questions
- How would you implement a
pending()method to check if there's a pending call? - Should cancel return anything? What would be useful?