Skip to the solution
HardFrontend7 min read

How do you implement a throttle function?

660 views

The problem

Question presented to candidate: "Implement a throttle function from scratch. Walk me through why it caps the call rate, then show me it actually limiting a burst of rapid calls."

What a strong answer should cover:

  • A closure holding a boolean cooldown flag (or, in an alternative implementation, a "last run timestamp").
  • On each call: if currently in cooldown, ignore the call entirely; otherwise run the wrapped function immediately and enter cooldown for the configured interval.
  • This means the FIRST call in a burst fires immediately (the "leading edge") by default, unlike debounce which always waits.
  • The cooldown-flag version and the last-run-timestamp version are both correct, common implementations with a real tradeoff between them, not just stylistic variants.
  • Real verification: proving with actual timestamps that a rapid burst produces a genuinely capped number of effect calls, spread at roughly the configured interval.

Clarifying questions expected:

  • "Should this fire on the leading edge, the trailing edge, or both?" (a strong candidate flags that the simplest version only does leading, and that configurable edges are a natural, common follow-up)

Code / implementation expected: Yes β€” a full working throttle implementation, executed with a rapid-fire burst and real observed timestamps proving the capped call rate.

  • throttle

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.

JavaScriptThrottle from scratch: 15 rapid calls capped to 4 (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 139 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 nextHard

What is ShadowRealm and how does it provide true JavaScript sandboxing?

Continue