FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Throttle

15mins

Throttling is a technique to limit how often a function executes.
When a function is throttled with a wait time of X ms:

  • The function can run immediately the first time.
  • Further calls within the next X ms are ignored.
  • Once X ms have passed since the last call, the function can run again.

Your task: Implement throttle(fn, wait) which:

  • Accepts a callback fn and a wait duration wait in ms.
  • Returns a throttled version of fn that respects the rules above.

Example

let i = 0; function increment() { i++; } const throttledIncrement = throttle(increment, 100); // t = 0 → call runs immediately, i = 1 throttledIncrement(); // t = 50 → ignored (less than 100ms since last run), i = 1 throttledIncrement(); // t = 101 → allowed (more than 100ms since last run), i = 2 throttledIncrement();

Follow-up:
Enhance throttle to support:

  • cancel() method (clear pending executions).
  • leading and trailing options (decide whether the function runs immediately, at the end, or both).

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests