Skip to curriculum
Jump to the editor

15.4. Throttle

Medium
Topics

This question is in

15. Debounce and throttle
15–25 min

Some events fire far more often than the page can usefully react: scroll and mousemove can fire dozens of times per frame of movement. Debouncing them would be wrong, because the page must react while the user scrolls, not only after. Throttling keeps the reaction going, but at a steady, limited rate: run now, then at most once every wait milliseconds.

Write throttle(fn, wait) in throttle.js. This is the simplest throttle: calls that come too soon are dropped. (Problem 15.5 adds a final, trailing run and options.)

Signature

JAVASCRIPT
function throttle(fn, wait) // returns a function
  • fn: the function to run.
  • wait: the minimum time between two runs, in milliseconds. A missing wait counts as 0.
  • The returned function returns undefined.

Requirements

  1. The first call runs fn at once.
  2. After a run, every call is dropped until wait ms have passed since that run; a call 1 ms too early is dropped, a call exactly wait ms later runs.
  3. The wait counts from the last run: dropped calls do not extend it.
  4. Dropped calls are gone: they never run later, and no timer is left behind.
  5. fn receives the this and every argument of the call that runs it.
  6. Each throttled function has its own state.
  7. With wait 0 (or no wait), every call runs.
  8. The throttled function returns undefined.

Examples

JAVASCRIPT
const onScroll = throttle(() => console.log("scroll at", Date.now() % 100000), 100);
// scroll events every 10 ms for one second:
// fn runs at 0, 100, 200, …, 900 ms: 10 times instead of 100
JAVASCRIPT
const log = throttle((value) => console.log(value), 100);
log("a");   // at 0 ms: "a"
log("b");   // at 50 ms: dropped
log("c");   // at 120 ms: "c" (120 ms after the run at 0)
JAVASCRIPT
const press = throttle(() => console.log("pressed"), 0);
press(); press(); // "pressed" twice: wait 0 drops nothing

Environment

  • Plain JavaScript in a browser page; the tests call the global throttle from throttle.js.
  • The tests run on a virtual clock that replaces Date.now, performance.now, setTimeout and clearTimeout. The clock starts at 0 ms.
  • A trailing run with the last dropped call, and leading/trailing options, are problem 15.5.

Hints

  1. What does the throttled function need to remember between calls to decide whether a call is too soon?
  2. Which value should that memory start with so the very first call always runs, even at time 0?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…