Skip to the solution
MediumFrontend6 min read

Implement debounce() with leading/trailing and cancel/flush

553 views

The problem

Problem, as an interviewer would state it: "Implement debounce(fn, wait, options) — delay calling fn until wait ms have passed with no new calls. Support a leading option (fire on the first call of a burst), a trailing option (fire on the last), and .cancel()/.flush() methods on the returned function."

Examples:

Code
const d = debounce(save, 300);
d(); d(); d(); // rapid calls -> save() runs once, 300ms after the LAST call
d.cancel(); // pending call is discarded

Clarifying questions expected:

  • If both leading and trailing are true, should the function fire TWICE for a single burst (once immediately, once at the end)?
  • Does this/arguments binding need to be preserved for the eventually-invoked call?
  • What should .flush() do if nothing is currently pending?

Code / implementation expected: Yes — real, direct proof of all 4 real modes (trailing-only, leading-only, cancel, flush) plus the leading+trailing combination.

  • debounce
  • timers
  • closure

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

6 min read · 9 sections

Run the code

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

JavaScriptReal, direct proof: debounce() correctly handles trailing-only, leading-only, cancel(), flush(), and leading+trailing combined

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 112 of 154 in JavaScript coding

Keep your momentum going.

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

Up nextMedium

Implement a Range Class Using the Iterator Protocol Manually (No Generator Functions Allowed)

Continue