AI Hints
Home›JavaScript Tutorial›Practice Projects 3
JavaScript · Lesson 122 of 138

Practice: Debounced Search

Wait for a pause.

⏱ 2 min read▶ Video at 2:26:31🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A search box that runs a search on every key press can send dozens of requests while you're still typing. A better idea is to wait until you pause. That trick is called debouncing, and it's a favourite interview question too.

Practice: Debounced Search
From the video: Practice: Debounced Search
  • Search on every key?
  • Too many requests
  • Wait for a pause: debounce

Debounce

Debounce takes a function and a delay, and returns a new function. Each call clears the previous timer, and starts a new one. So the real function only runs once the calls stop for the whole delay. Here we fire five quick calls, and the search runs just once, with the last value. Run it.

app.jsjavascript
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

const search = debounce((q) => console.log("Searching for:", q), 300);

for (const q of ["j", "ja", "jav", "java", "javas"]) {
  console.log("typed", q);
  search(q);
}
Output
typed j
typed ja
typed jav
typed java
typed javas
Searching for: javas

On a page

On the page, the input event calls the debounced function. The list filters a set of fruit names, and only redraws once you stop typing for a moment. A counter shows how many times the filter really ran. We typed six letters quickly, and it ran only once.

index.htmlpython
<link rel="stylesheet" href="style.css">
<input id="q" placeholder="Search fruit"> <span id="runs"></span>
<ul id="list"></ul>
<script>
  const fruit = ["apple", "apricot", "banana", "blueberry", "cherry", "grape"];
  let count = 0;
  const debounce = (fn, ms, t) => (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
  const show = debounce((text) => {
    runs.textContent = `filter ran ${++count} time(s)`;
    list.replaceChildren(...fruit.filter(f => f.includes(text)).map(f => {
      const li = document.createElement("li"); li.textContent = f; return li;
    }));
  }, 300);
  q.addEventListener("input", () => show(q.value));
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#q", "text": "apr"}, {"type": "#q", "text": "ico"}, {"wait": 500}]

Summary

Debounce waits until calls stop before running a function, which saves work and requests. Next, writing automated tests.

Key takeaways
  • clearTimeout, setTimeout
  • Runs after a pause
  • Great for search boxes
Next up: Practice: Unit Tests — checking your code automatically