Problem Statement
In our production systems, we sometimes need immediate feedback for the first user interaction, but want to debounce subsequent rapid calls. Implement a leading-edge debounce that fires immediately on the first call.
Requirements
Implement a debounceLeading(func, wait) function that:
- Invokes
funcimmediately on the first call - Ignores subsequent calls within the
waitperiod - After the wait period, the next call triggers immediately again
- Preserves
thiscontext and arguments
Example Usage
const submitForm = (data) => {
console.log(`Submitting: ${JSON.stringify(data)}`);
};
const debouncedSubmit = debounceLeading(submitForm, 1000);
debouncedSubmit({ id: 1 }); // Logs immediately: "Submitting: {"id":1}"
debouncedSubmit({ id: 2 }); // Ignored (within 1000ms)
debouncedSubmit({ id: 3 }); // Ignored (within 1000ms)
// After 1000ms...
debouncedSubmit({ id: 4 }); // Logs immediately: "Submitting: {"id":4}"Real-world Context
Leading-edge debounce is essential for:
- Button click handlers (prevent double-submit but respond instantly)
- Like/upvote buttons (immediate UI feedback)
- Navigation actions (instant response, prevent rapid navigation)
Follow-up Questions
- How would you extend this to support both leading and trailing edge?
- What edge cases should you handle for the timing?