Throttle with Leading and Trailing
Problem statement
Implement throttle(func, wait, options). Throttling ensures a function runs at most once per wait window.
Options
leading: whether to run on the first call in a window. Defaults totrue.trailing: whether to run once more with the latest arguments after the window ends. Defaults totrue.
Requirements
- Preserve
thisand latest arguments. - Support leading-only, trailing-only, both, and neither.
- Add
cancel()to clear pending trailing calls. - Return the latest invocation result from the wrapper.
Requirements & constraints
- Do not use lodash or external libraries.
- Support both leading and trailing options.
- Expose a cancel method.
How to approach Throttle with Leading and Trailing
The strategy an interviewer expects you to reach for.
Throttle with leading/trailing options is the “scroll handler” API: fire immediately, then at most once per window, optionally catching the last call. Naive move Ignore calls inside the window entirely. Users lose the final scroll position update. Where it breaks Leading-off should not fire at the start. Trailing-off should not schedule the tail. Rapid calls must refresh the trailing timer with the latest args. The fix Track lastCallTime, lastArgs, and a timer. If enough time passed and leading is on, invoke now. Else if trailing is on, schedule one timeout for the remaining wait with the newest args. Remember: Trailing exists to keep the last event; leading exists for instant feedback. Say this in the interview: I'd track last invoke time, optionally fire immediately on the leading edge, and schedule a single trailing call with the latest args when calls keep arriving inside the window.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.