Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
15.4. Throttle
Medium
Topics
This question is in
15. Debounce and throttleSome 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
function throttle(fn, wait) // returns a functionfn: the function to run.wait: the minimum time between two runs, in milliseconds. A missingwaitcounts as0.- The returned function returns
undefined.
Requirements
- The first call runs
fnat once. - After a run, every call is dropped until
waitms have passed since that run; a call 1 ms too early is dropped, a call exactlywaitms later runs. - The wait counts from the last run: dropped calls do not extend it.
- Dropped calls are gone: they never run later, and no timer is left behind.
fnreceives thethisand every argument of the call that runs it.- Each throttled function has its own state.
- With
wait0 (or nowait), every call runs. - The throttled function returns
undefined.
Examples
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 100const 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)const press = throttle(() => console.log("pressed"), 0);
press(); press(); // "pressed" twice: wait 0 drops nothingEnvironment
- Plain JavaScript in a browser page; the tests call the global
throttlefromthrottle.js. - The tests run on a virtual clock that replaces
Date.now,performance.now,setTimeoutandclearTimeout. The clock starts at 0 ms. - A trailing run with the last dropped call, and
leading/trailingoptions, are problem 15.5.
Hints
- What does the throttled function need to remember between calls to decide whether a call is too soon?
- 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…