Throttle (leading + trailing)
25 min·senior·closures · timers
Implement throttle(fn, wait) such that:
- The first call fires immediately (leading edge)
- Subsequent calls within
waitms are ignored, except the last one — it fireswaitms after the last call (trailing edge) - Forwards args + preserves
this
const t = throttle((x) => log(x), 100); t(1); t(2); t(3); // log(1) immediately // log(3) ~100ms later
Analyze: time per call, space per throttled fn.
expected time · O(1) per call
expected space · O(1) per throttled fn
4 lines
⏵ run · no run yet · ctrl+enter