CodePark/ problems / throttle (leading and trailing)
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Timers and scheduling

throttle (leading and trailing)

hardabout 30 minutes in an interview

Implement throttle(fn, wait). It returns a new function that calls fn at most once per window of wait ms. A window is a period of time that starts when fn runs.

  • Idle: when no window is open, a call runs fn immediately. That opens a window of wait ms.
  • Inside a window: calls don't run. Only the latest call is remembered, with its arguments and this.
  • Window ends: if any call came in during the window, run fn once with the latest remembered call. That run opens a new window. If no call came in, go back to idle.
  • The throttled function returns nothing.
Input: const t = throttle(log, 100); t('a') at 0 ms, t('b') at 30, t('c') at 60 Output: log('a') at 0, log('c') at 100
Input: t('a') at 0, t('b') at 50, t('c') at 120 Output: log('a') at 0, log('b') at 100, log('c') at 200The run at 100 opens a new window, so 'c' waits until 200.
Input: t('a') at 0, t('b') at 150 Output: log('a') at 0, log('b') at 150The window closed at 100 with nothing waiting, so 'b' runs at once.