Problem Statement
Sometimes we need to immediately execute a pending debounced function—for instance, when a form is submitted or before the page unloads. Implement a debounce with both cancel and flush capabilities.
Requirements
Implement a debounce(func, wait) function that returns a debounced function with:
cancel()- cancels pending invocation without executingflush()- immediately executes pending invocation (if any)- Flush should be a no-op if nothing is pending
- After flush, the timer should be cleared
Example Usage
Real-world Context
- Auto-save with manual save option
- Form validation with submit button
- Analytics batching with page unload
Follow-up Questions
- Should flush return the result of the function call?
- How would you handle async functions with flush?