27Implement throttle() with leading and trailing options
mediumAbout 35 minutesCodingtimersclosuresperformance
Problem
Implement throttle(fn, wait, { leading = true, trailing = true } = {}). The throttled function calls fn at most once per wait milliseconds, however often it is called.
leading: truecallsfnimmediately on the first call of a quiet period.trailing: truemakes sure the last call made during a waiting period is not lost:fnruns with its arguments when the period ends.
Also add cancel(), which drops any pending trailing call.
const onScroll = throttle(() => updateProgressBar(), 100);
window.addEventListener("scroll", onScroll);Requirements
- Call
fnwith the arguments andthisof the call that triggered it. - A trailing call starts a new waiting period, so two calls are never closer than
waitapart. - With
leading: false, the first call only schedules a trailing call. - If nothing was called during a waiting period, no trailing call happens.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
A timer represents the current waiting period. While it runs, fn must not be called directly. When it is null, the throttle is idle.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.