×

javascript · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.