Skip to the solution
MediumFrontendNetflixAsked in 2024, 20227 min read

Debounce vs throttle — implement debounce

3.7k views

The problem

Question presented to candidate: "Implement a debounce function from scratch. Walk me through why it works, then show me it actually collapsing a burst of rapid calls into one."

What a strong answer should cover:

  • A closure holding a single timer id across calls.
  • Every call clears the previous pending timer, then starts a brand-new one — this is the entire mechanism.
  • The wrapped function only actually runs once no new call has arrived within the delay window, and it runs with the arguments from the LAST call, not the first.
  • Correct this handling if the debounced function needs to be used as a method (use a regular function for the wrapper and fn.apply(this, args), not an arrow function, if the caller relies on dynamic this).
  • Real verification: proving with actual timestamps that a rapid burst produces exactly one effect call, not an assumption from reading the code.

Clarifying questions expected:

  • "Should the debounced function support being called as an object method (i.e. does this need to work), or is a plain top-level function enough?"
  • "Do you want a .cancel() method as part of this, or is that a separate follow-up?" (confirms scope — the advanced .cancel() variant is a distinct question in this bank)

Code / implementation expected: Yes — a full working debounce implementation, executed with a rapid-fire burst and real observed timestamps proving only the last call's effect fires.

  • javascript
  • performance

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptDebounce from scratch: 5 rapid calls collapse into 1 (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 42 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do you implement infinite currying in JavaScript?

Continue