Skip to the solution
MediumFrontend5 min read

Implement throttle(func, wait, {leading, trailing})

1.0k views

The problem

Problem, as an interviewer would state it: "Implement throttle(fn, wait, options) — guarantee fn runs at most once every wait ms, even under continuous, rapid calls, with configurable leading/trailing edges."

Examples:

Code
const t = throttle(onScroll, 100);
window.addEventListener("scroll", t);
// fires at most once per 100ms while scrolling continuously, not once per pixel

Clarifying questions expected:

  • Does the FINAL call of a continuous burst need to be captured (trailing edge), or is it acceptable to drop it?
  • Should the first call fire immediately (leading edge), or only after the first full window?
  • Is wait a fixed window from the FIRST call, or does it reset on every subsequent call (which would make this debounce, not throttle)?

Code / implementation expected: Yes — real, direct proof via a timed burst that both the leading and trailing edges fire correctly and calls are correctly rate-limited.

  • throttle
  • timers
  • leading-trailing

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

5 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: throttle() correctly rate-limits a continuous burst while still capturing the leading and trailing edges

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 90 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

Build an Undo/Redo Command Stack for a Text Editor

Continue