Polski

Debounce and throttle

Two classic frontend higher-order functions – debounce (call after silence) and throttle (at most once per period) – with cancel, flush, preserved this and injected timers.

medium · typescript · javascript · 20 XP

A search box should not send a request on every keystroke, and a scroll handler should not recompute the layout 120 times per second. Two wrapper functions help, and frontend interviews ask about them all the time. The task is about JavaScript/TypeScript – timers, closures and this.

Task

Both functions take an optional timer = { setTimeout(fn, ms), clearTimeout(id) } object (the global setTimeout/clearTimeout by default) – the tests plug in fake timers and control time.

debounce(fn, waitMs, timer?) returns a function that:

  • calls fn only after waitMs ms of silence – every new call during that time postpones it,
  • passes fn the arguments and this of the last call,
  • has a cancel() method – drops the pending call,
  • has a flush() method – if a call is pending, runs fn immediately (and cancels the timer); otherwise does nothing.

throttle(fn, intervalMs, timer?) returns a function that:

  • on the first call (when nothing is in progress) calls fn immediately and starts an intervalMs period,
  • remembers calls made during the period (the last arguments and this); at the end of the period, if there was at least one such call, calls fn once with the last arguments and starts another period,
  • when a period passes without calls, goes back to idle – the next call is immediate again,
  • has a cancel() method – drops the remembered call and goes back to idle.

Example

waitMs = intervalMs = 100, calls with arguments 1 (0 ms), 2 (30 ms), 3 (60 ms):

FunctionCalls of fn
debouncefn(3) at 160 ms
throttlefn(1) at 0 ms, fn(3) at 100 ms

Constraints

  • Up to 100,000 calls in the performance test; at any moment at most one timer should be active.

Expected complexity

Every call of the wrapped function O(1).

Topics: Decorator