Skip to curriculum
Jump to the editor

15.5. Throttle with leading and trailing options

Hard
Topics

This question is in

15. Debounce and throttle
30–45 min

A throttle that only drops calls (problem 15.4) loses the last one: if the user stops scrolling 60 ms after a run, the final scroll position is never handled. A complete throttle keeps the latest dropped call and runs it when the wait is over, the trailing run. Some uses need the opposite control: a "refresh token" button should act on the first click (the leading run) and ignore the rest; a resize handler may prefer to skip the leading run and only act on the latest size. And code that tears down a page needs to cancel or flush what is waiting.

Write throttle(fn, wait, options) in throttle.js, with these rules.

Signature

JAVASCRIPT
function throttle(fn, wait, options = {}) // returns a throttled function

throttled(...args)   // returns the result of fn's most recent run
throttled.cancel()   // drops the saved call and closes the window
throttled.flush()    // runs the saved call now; returns the latest result
  • options.leading (default true), options.trailing (default true).
  • The throttle is either idle or has a window open. A window lasts wait ms.

Requirements

  1. A call while idle opens a window. With leading, it also runs fn at once and returns the new result.
  2. With trailing, every call made while a window is open is saved, replacing the previous one; with leading off, the call that opens the window is saved too. Without trailing, those calls are dropped.
  3. When a window closes: if a call is saved, fn runs with its this and arguments, and a new window opens at once. Otherwise the throttle becomes idle, with no timer left.
  4. As a result, fn never runs twice within wait ms (except through flush), and in a steady stream of calls the latest one always runs, when trailing is on.
  5. With both options off, fn never runs.
  6. Every call returns the result of fn's most recent run, or undefined before the first.
  7. cancel() stops the timer, drops the saved call and makes the throttle idle, so the next call is like the first.
  8. flush(): if a call is saved, run it now, then open a new window from now (replacing the old one). It returns the latest result. With nothing saved it runs nothing.
  9. Each throttled function has its own state.
  10. fn may call back into the throttle while it runs. The window opens before fn runs, so a call fn makes is a call during that window (saved or dropped, never run at once), and a cancel() it makes leaves the throttle idle with no timer.

Examples

JAVASCRIPT
const onScroll = throttle((y) => console.log("at", y), 100);
// scroll events every 20 ms from 0 to 480 ms, with y = the event's time:
// "at 0" at 0 ms, "at 80" at 100, "at 180" at 200, … "at 480" at 500: the last position is shown
JAVASCRIPT
const t = throttle((n) => console.log(n), 100);
t(1);  // at 0 ms: 1
t(2);  // at 50 ms: saved; runs at 100 ms, which opens a new window
t(3);  // at 150 ms: saved; runs at 200 ms, not at once
JAVASCRIPT
const refresh = throttle(() => console.log("refreshing"), 1000, { trailing: false });
refresh(); refresh(); refresh(); // "refreshing" once; the other clicks are dropped
JAVASCRIPT
const resize = throttle((width) => console.log(width), 200, { leading: false });
resize(800); resize(760); resize(700); // nothing yet; at 200 ms: 700

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 setTimeout, clearTimeout and Date.now. Timers due at a moment run before a call made at that same moment.
  • wait is a positive number of milliseconds; 0, a missing wait, and maxWait are out of scope.
  • These rules are close to lodash's throttle, but not identical: here a trailing run always opens a new window.

Hints

  1. What does the throttle need to remember: when it last ran, or simply whether a window is open?
  2. When a window closes with a saved call, why must a new window open right away?

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…