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
fnimmediately. - Calls made during the cooldown do not run right away; the arguments and
thisof the last such call are saved, andfnruns 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.