Debounce - Problem

Given a function fn and a time in milliseconds t, return a debounced version of that function.

A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.

Example: If t = 50ms, and the function was called at 30ms, 60ms, and 100ms:

  • The first 2 function calls would be cancelled
  • The 3rd function call would be executed at 150ms

If instead t = 35ms:

  • The 1st call would be cancelled
  • The 2nd would be executed at 95ms
  • The 3rd would be executed at 135ms

Note: You cannot use lodash's _.debounce() function.

Input & Output

Example 1 — Basic Debouncing
$ Input: t = 50, calls at [30ms, 60ms, 100ms]
Output: Function executes once at 150ms
💡 Note: First two calls are cancelled by subsequent calls. The third call executes after 50ms delay (at 150ms total).
Example 2 — Shorter Delay
$ Input: t = 35, calls at [30ms, 60ms, 100ms]
Output: Function executes at 95ms and 135ms
💡 Note: First call cancelled. Second call executes at 95ms (60+35). Third call executes at 135ms (100+35).
Example 3 — Single Call
$ Input: t = 100, single call at 50ms
Output: Function executes at 150ms
💡 Note: With no subsequent calls to cancel it, the function executes after the full delay.

Constraints

  • 0 ≤ t ≤ 1000
  • fn is a valid function
  • At most 10 function calls will be made

Visualization

Tap to expand
Debounce: Transform Rapid Calls into Delayed Single ExecutionInput Functionfn = (x) => x * 2t = 50msDebounce ProcessCancel previous timerSet new timer (t ms)Debounced FunctionDelayed executionCancellable callsExample Timeline (t=50ms)Call @30msCancelledCall @60msCancelledCall @100msExecute @150ms🎯 Key Insight: Each call resets the timer, ensuring only the final call executes
Understanding the Visualization
1
Input
Function fn and delay time t in milliseconds
2
Process
Return debounced version that delays and cancels previous calls
3
Output
New function that implements debouncing behavior
Key Takeaway
🎯 Key Insight: Use closure with timer reference to cancel previous executions and delay the current one
Asked in
Google 35 Facebook 28 Amazon 22 Netflix 18
28.5K Views
High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen