Skip to content
Onsite

Throttle

MediumP1Coding

Implement throttle(fn, wait).

It returns a function that calls fn at most once every wait milliseconds. Use the leading edge with a trailing call:

  • The first call runs fn immediately.
  • Calls made during the cooldown do not run right away; the arguments and this of the last such call are saved, and fn runs with them once, when the cooldown ends.
  • After that trailing call, a new cooldown starts.

Also add cancel() to the returned function; it clears any pending trailing call and resets the cooldown.

Example 1

Input
const t = throttle(log, 100); t(1); t(2); t(3);
Output
log(1) runs now, log(3) runs after about 100 ms
Why
2 is dropped; only the last call during the cooldown is kept.

Constraints

  • 0 <= wait <= 10^4
  • Use setTimeout and clearTimeout; Date.now is allowed but not required.

Hints

Run checks the 3 visible tests, Submit all 7.