Throttle
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a function that runs `fn` at most once every `wait` milliseconds, on the leading edge. The first call runs `fn` at once with the call's arguments and returns its result. A call that arrives less than `wait` ms after the last run is dropped and returns `undefined`. A call exactly `wait` ms (or more) after the last run runs again. There is no trailing call for dropped calls. Compare times with `Date.now()`. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.
What this exercise teaches
Storing the time of the last run and comparing with >= makes a call exactly wait ms later run, which a > comparison drops. Debounce waits for quiet and runs at the end; throttle runs first and ignores the rest of the window.
A hint if you get stuck
Keep `last`, the time of the last run, starting at `-Infinity`. In the returned function read `Date.now()`, and only when `now - last >= wait` update `last` and call `fn` with the arguments.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Async and functions
- A counter with private stateFree
- Sleep with a PromiseFree
- Retry a failing callFree
- Promise.all with a concurrency limitFree
- DebounceFree
- MemoizeFree
- Run only onceFree
- Pipe functions togetherFree
- Timeout wrapperFree
- Run tasks in sequenceFree
- Curry a functionFree
- Event emitterFree
- LRU cacheFree
- Write your own Promise.allFree
- Callback style to a PromiseFree