javascript · level 3 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Debouncing waits for the typing to stop before doing the work.
A search box that asks the server on every key press sends ten requests for one word. it instead: each call restarts a short timer, and only when calls stop for, say, 200 milliseconds does the real work run, once.
setTimeout gives back an id, and cancels that timer before it fires. A debounce wrapper keeps the latest id in a closure and cancels it on every new call. Its cousin, , runs at most once per stretch of time instead.
function debounce(task, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => task(...args), ms);
};
}
const search = debounce((text) => console.log(`Searching for "${text}"`), 200);
search("c");
search("ca");
search("cat");
setTimeout(() => search("cats"), 400); Debounce suits things that should happen after a burst ends, like searching, saving a draft or resizing.
guess first
Four saves in two bursts. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function debounce(task, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => task(...args), ms);
};
}
const save = debounce((n) => console.log(`saved draft ${n}`), 100);
save(1);
setTimeout(() => save(2), 30);
setTimeout(() => save(3), 300);
setTimeout(() => save(4), 330);
your turn
Your turn. Throttle a fire button.
First, unlock the throttle when its wait is over. Then choose a delay for the last shot that is longer than the 100 ms window.
fix it
The layout runs three times. Can you fix it?
- Every call starts a timer. Does anything ever stop the earlier ones?
- A debounce must cancel the previous timer before starting a new one.
- Add
clearTimeout(timer);as the first line inside the arrow function, then press run.
nailed it
your code waits for the right moment. :D
- Debounce runs once, after the calls stop arriving.
- Throttle runs at most once in each stretch of time.
clearTimeoutcancels a timer before it fires.
new words in your collection
- debounce
- throttle
- clearTimeout
This lesson isn’t saved. A free account remembers every lesson you finish.