Imagine you're developing a search feature for an e-commerce website. Every time a user types a character, your code wants to make an API call to fetch search results. But if a user types quickly, you'd end up making dozens of unnecessary API calls!
Debouncing is a technique that solves this problem by delaying function execution and canceling previous calls if new ones arrive within a time window.
Given a function fn and a time delay t milliseconds, return a debounced version of that function. The debounced function should:
- Delay execution by
tmilliseconds - Cancel previous executions if called again within the delay window
- Pass through all parameters to the original function
Example: If t = 50ms and calls happen at 30ms, 60ms, and 100ms:
- Call at 30ms → Scheduled for 80ms, but gets cancelled
- Call at 60ms → Scheduled for 110ms, but gets cancelled
- Call at 100ms → Finally executes at 150ms
Input & Output
Visualization
Time & Space Complexity
Each function call just sets/clears a timeout, which are constant time operations
Only stores a single timeout ID regardless of number of calls
Constraints
- 0 ≤ t ≤ 1000 (delay in milliseconds)
- Function can be called with any number of arguments
- Must preserve 'this' context of original function calls
- Should handle rapid successive calls efficiently