coding round · ~20 min
JavaScriptintermediate

Implement throttle

Write throttle(fn, wait) that returns a throttled version of fn which runs at most once every wait ms:

  • the first call runs fn immediately (the leading call)
  • calls made during the wait are held back; when the wait ends, fn runs once more with the latest arguments and this (the trailing call)
  • a trailing call starts a new wait of its own, so fn never runs twice within wait ms
  • if a whole wait passes without any calls, the throttle resets and the next call runs immediately again

Example with wait = 100: t(1) at 0ms runs fn(1) right away; t(2) at 20ms and t(3) at 50ms are held back; at 100ms fn(3) runs, and fn(2) is never called.

Define throttle in the editor. 7 tests will call it.

read the related note →

solution.js
function throttle(fn, wait) {
  // Call fn right away on the first call, then at most once per `wait` ms.
  // Calls made while waiting should lead to one trailing call
  // with the latest arguments when the wait is over.
}

Tests⌘/Ctrl + Enter to run

calls fn immediately on the first call
makes one trailing call with the latest arguments
makes no trailing call when called only once
runs immediately again after a quiet window
the trailing call starts a new window
never calls fn more than once per wait during a burst
preserves this and arguments for leading and trailing calls
esc