JavaScript Project: Debounced Search
A debounced search waits for quiet before it searches. Fast typing fires the search once, for the last query only.
The debounce factory
debounce takes a function and a delay. It returns a new function that waits for quiet before it runs.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(function () {
fn(...args);
}, delay);
};
}
function say(message) {
console.log(message);
}
const saySoon = debounce(say, 50);
saySoon("first");
saySoon("second");A search over a small list
search filters a small list of book titles. It keeps the titles that hold the query text.
const books = ["JavaScript Basics", "JavaScript Patterns", "Python Basics", "CSS Guide"];
function search(query) {
const hits = books.filter(function (book) {
return book.toLowerCase().includes(query.toLowerCase());
});
console.log(JSON.stringify(hits));
}
search("javascript");Rapid typing, one search
Three calls arrive in a row. Each one cancels the timer of the call before it, so only the last query runs.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(function () {
fn(...args);
}, delay);
};
}
function search(query) {
console.log("Searching for: " + query);
}
const debouncedSearch = debounce(search, 50);
debouncedSearch("ja");
debouncedSearch("jav");
debouncedSearch("java");Example
const books = ["JavaScript Basics", "JavaScript Patterns", "Python Basics", "CSS Guide", "Java in Depth"];
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(function () {
fn(...args);
}, delay);
};
}
function search(query) {
const hits = books.filter(function (book) {
return book.toLowerCase().includes(query.toLowerCase());
});
console.log("Search: " + query + " -> " + JSON.stringify(hits));
}
const debouncedSearch = debounce(search, 50);
debouncedSearch("ja");
debouncedSearch("jav");
debouncedSearch("java");Key points
- Debounce: waiting for a pause before running a function
- Timer: a pending call that setTimeout schedules and clearTimeout cancels
- The closure holds the timer, so each call can cancel the one before it.
- A search runs only after typing stops for the delay.
- Rapid calls cancel each other, and only the last call runs.
In this example, the program builds a debounced search over five book titles. Three quick calls arrive in a row, and each one cancels the timer of the call before it. Only the last query runs, so the log shows one search for java with three matching titles.
Note
The search function itself never changes. Debounce only controls when it runs.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does the log show after three rapid calls to a debounced search?