Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
15.1. Debounce
Medium
Topics
This question is in
15. Debounce and throttleA search box sends a request on every keystroke. Type "react" and five requests leave, though only the last one matters. Debouncing fixes that: the work waits until the calls stop for a while, then runs once.
Write debounce(fn, wait) in debounce.js. It returns a new function. Each call to that function restarts a wait of wait milliseconds; when a whole wait passes with no new call, fn runs once, with the this and the arguments of the last call.
Signature
function debounce(fn, wait) // returns a functionfn: the function to run.wait: milliseconds of quiet beforefnruns. A missingwaitcounts as0.- The returned function returns
undefined:fnhas not run yet when it returns.
Requirements
debouncereturns a function, and calling it does not callfnstraight away.- After a single call,
fnruns exactlywaitms later: not 1 ms earlier. - A burst of calls runs
fnonce,waitms after the last call. A call during the wait restarts it. fnreceives every argument of the last call, and thethisof the last call (so it works as an object's method).- Each function that
debouncereturns has its own timer: debouncing two handlers never cancels one with the other. - After
fnruns, the next call starts a new wait, so a second burst runsfnagain. - Only one timer is ever waiting, and none is left once
fnhas run. - With
wait0,fnstill runs in a later timer task, never during the call.
Examples
const log = debounce((text) => console.log("search:", text), 300);
log("r"); // at 0 ms
log("re"); // at 100 ms: the wait starts again
log("rea"); // at 200 ms: the wait starts again
// at 500 ms (200 + 300): "search: rea", onceconst box = {
name: "box",
save: debounce(function (value) { console.log(this.name, value); }, 100),
};
box.save(1);
box.save(2);
// 100 ms later: "box 2"const a = debounce(() => console.log("a"), 100);
const b = debounce(() => console.log("b"), 100);
a(); // at 0 ms
b(); // at 50 ms
// "a" at 100 ms, "b" at 150 ms: separate timersEnvironment
- Plain JavaScript in a browser page; the tests call the global
debouncefromdebounce.js. - The tests run on a virtual clock that replaces
setTimeoutandclearTimeout, so use those (norequestAnimationFrame, no busy loops). - Leading-edge calls,
maxWait,cancelandflushare not part of this problem: they are problem 15.2.
Hints
- The timer has to survive between calls, but belong to one debounced function. Where can a variable live so that happens?
- Arrow functions take
thisfrom where they are written. Which kind of function gets the caller'sthis?
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…