call(back)
FrontendmediumSign in to star problems

Implement Throttle

Write throttle(fn, wait): the returned function calls fn at most once per wait ms.

const onScroll = throttle(update, 100);
// calls at 0, 30 and 60 ms  ->  update runs at 0 (with the first call's arguments)
//                               and at 100 (with the call at 60's arguments)

Rules

  • The first call fires immediately.
  • Calls inside the window collapse into one trailing fire at the window's end, with the latest arguments; that fire starts the next window.
  • A call after a quiet window fires immediately again.
  • Return a real function, not an arrow, so a caller's this is forwarded.

The grader replays timed call scripts on a virtual clock — setTimeout, clearTimeout, and Date.now are stubbed — so build on those, not on performance.now or promises. Each case's input is the wait and a script of [ms, "call", ...args] steps; the expected output lists every fire as {at, args}.

Hints

Hint 1

Track the time of the last fire. If wait ms have passed since then, fire now; otherwise arm a single trailing timer for the rest of the window.

Hint 2

Overwrite the saved arguments (and this) on every call so the trailing fire uses the newest ones, and record the fire time when the trailing call actually runs.

Asked at