Problem Statement
As a Staff Engineer, I often see performance issues in production caused by excessive function calls during user interactions like typing, scrolling, or resizing. Your task is to implement a debounce utility function that limits how often a function can be executed.
Requirements
Implement a debounce(func, wait) function that:
- Returns a new function that delays invoking
funcuntil afterwaitmilliseconds have elapsed since the last time the debounced function was invoked - The debounced function should receive all arguments passed to it
- The
thiscontext should be preserved
Example Usage
Real-world Context
At scale, this pattern is critical for:
- Search-as-you-type features (reducing API calls)
- Window resize handlers (preventing layout thrashing)
- Auto-save functionality (batching saves)
Follow-up Questions
- What is the time and space complexity of your solution?
- How does debounce differ from throttle?
- When would you choose debounce over throttle?