TryJS
Browser · HTML / CSS / JavaScriptFormsAsyncEventsUI

JavaScript Debounce Search — Interactive Input Example

Compare raw input events with delayed work in a live search box.

Loading playground…

The live editor loads here with JavaScript enabled.

Run in Playground ↗

The original source and explanation are available below.

Changes here stay separate from your main playground. Use Open in TryJS inside the editor to keep working with your changes.

Useful? Help keep TryJS free and independent.

Support TryJS

What to expect

Every input updates the first counter. The delayed counter updates only after you stop typing for 400 milliseconds.

About this example

Debounce waits for a quiet interval before doing work. A search field is a useful way to see the difference between every keystroke and the work you choose to perform. This demo updates local text instead of calling an API.

How It Works

Cancel the previous timer

Each input event clears the earlier timeout and starts another one. Rapid input keeps postponing the delayed update.

Run after a pause

When no new input arrives during wait, the callback updates the delayed result and its counter.

Read the original source

This is the starting code. Your edits stay in the live editor above.

HTML

<main><h1>Debounce a search</h1><label>Search <input id="search" placeholder="Start typing…" /></label><p>Input events: <output id="raw">0</output></p><p>Delayed updates: <output id="delayed">0</output></p><p aria-live="polite">Result: <strong id="result">Waiting for input</strong></p></main>

CSS

* { box-sizing: border-box; }
body { margin: 0; padding: 24px; background: #faf8f0; color: #222; font: 15px/1.6 system-ui, sans-serif; }
h1 { font-size: 24px; line-height: 1.2; margin: 0 0 12px; }
p { margin: 8px 0 16px; }
button, input { font: inherit; }
button { padding: 9px 16px; border: 1px solid #b9a200; border-radius: 7px; background: #f0d000; color: #222; cursor: pointer; }
button:disabled { opacity: .6; cursor: wait; }
input { max-width: 100%; padding: 9px 12px; border: 1px solid #aaa; border-radius: 7px; }
small { color: #595959; }
output { font-variant-numeric: tabular-nums; }

JavaScript

const wait = 400;
let timer;
let inputs = 0;
let updates = 0;
const search = document.querySelector("#search");
search.addEventListener("input", () => {
  document.querySelector("#raw").textContent = String(++inputs);
  clearTimeout(timer);
  timer = setTimeout(() => {
    document.querySelector("#delayed").textContent = String(++updates);
    document.querySelector("#result").textContent = search.value || "Empty search";
  }, wait);
});