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 Function INPUT function fn() Any function to debounce t = 50ms (delay) Function Calls Timeline 30ms Call 1 60ms Call 2 100ms Call 3 Input Parameters t: 50ms calls: [30, 60, 100] window: t ms after last call ALGORITHM STEPS 1 Call at 30ms Start timer for 50ms (would fire at 80ms) 2 Call at 60ms Cancel timer, restart (would fire at 110ms) 3 Call at 100ms Cancel timer, restart (will fire at 150ms) 4 No more calls Timer completes at 150ms fn() executes! Timer Reset Pattern Execute! FINAL RESULT Execution Timeline 30ms 60ms 100ms 150ms = Cancelled = Executed Output Executes at: 150ms Total executions: 1 OK 3 calls --> 1 execution Debounced successfully! Key Insight: Timer-Based Debouncing Debouncing uses clearTimeout() and setTimeout() to reset the timer on each call. The function only executes when there's a "quiet period" of t milliseconds with no new calls. This is essential for rate-limiting events like keystrokes, scrolling, or window resizing. TutorialsPoint - Debounce | Timer-Based Debouncing Approach
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