Implement Throttle
Implement a throttle function that ensures a callback runs at most once per specified time interval, no matter how often it is called. Throttle is the natural counterpart to debounce and a very common interview question — typically used for scroll, resize, and mousemove handlers.
Examples
Input: throttle(fn, 1000) — called 10 times within 1 second
Output: fn is called once (leading edge), the rest are ignored
// The first call fires immediately; subsequent calls inside the window are dropped.
Input: throttle(fn, 200) with trailing edge — rapid calls then silence
Output: fn fires immediately, then once more with the latest args after 200 ms
// The trailing call guarantees the final state is not lost.
Constraints
- fn must run at most once per `limit` milliseconds.
- Preserve the original this context and forward all arguments.
- Bonus: support a trailing-edge call with the most recent arguments.
closuretimerhigher-order-functionperformancelodash
Important
Interview Tip
Be ready to contrast throttle vs debounce: throttle = at most once per interval (steady cadence); debounce = wait until activity stops. Start with the timestamp version, then add the trailing edge as the follow-up. Use cases: throttle a scroll handler, debounce a search input.
Approach: Timestamp (Leading)
Record the last run time; run fn only when at least `limit` ms have passed. Fires on the leading edge. The simplest correct answer.
Complexity
Time: O(1)Space: O(1)
Pros
- Minimal code
- Fires immediately (leading edge)
- Easy to explain
Cons
- Drops the final trailing call
- No cancel support