15.5. Throttle with leading and trailing options
Topics
This question is in
15. Debounce and throttleA 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
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 resultoptions.leading(defaulttrue),options.trailing(defaulttrue).- The throttle is either idle or has a window open. A window lasts
waitms.
Requirements
- A call while idle opens a window. With
leading, it also runsfnat once and returns the new result. - With
trailing, every call made while a window is open is saved, replacing the previous one; withleadingoff, the call that opens the window is saved too. Withouttrailing, those calls are dropped. - When a window closes: if a call is saved,
fnruns with itsthisand arguments, and a new window opens at once. Otherwise the throttle becomes idle, with no timer left. - As a result,
fnnever runs twice withinwaitms (except throughflush), and in a steady stream of calls the latest one always runs, whentrailingis on. - With both options off,
fnnever runs. - Every call returns the result of
fn's most recent run, orundefinedbefore the first. cancel()stops the timer, drops the saved call and makes the throttle idle, so the next call is like the first.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.- Each throttled function has its own state.
fnmay call back into the throttle while it runs. The window opens beforefnruns, so a callfnmakes is a call during that window (saved or dropped, never run at once), and acancel()it makes leaves the throttle idle with no timer.
Examples
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 shownconst 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 onceconst refresh = throttle(() => console.log("refreshing"), 1000, { trailing: false });
refresh(); refresh(); refresh(); // "refreshing" once; the other clicks are droppedconst resize = throttle((width) => console.log(width), 200, { leading: false });
resize(800); resize(760); resize(700); // nothing yet; at 200 ms: 700Environment
- Plain JavaScript in a browser page; the tests call the global
throttlefromthrottle.js. - The tests run on a virtual clock that replaces
setTimeout,clearTimeoutandDate.now. Timers due at a moment run before a call made at that same moment. waitis a positive number of milliseconds; 0, a missingwait, andmaxWaitare out of scope.- These rules are close to lodash's
throttle, but not identical: here a trailing run always opens a new window.
Hints
- What does the throttle need to remember: when it last ran, or simply whether a window is open?
- 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