Problem
You are building a search-as-you-type box. Every keystroke currently fires an API request, so typing "react" sends five requests in under a second — wasting bandwidth, racing responses, and hammering your backend. You want to fire one request, only after the user pauses typing.
Implement debounce(fn, delay) that returns a debounced wrapper around fn.
- Each call to the wrapper resets an internal timer.
fnruns once, with the most recent arguments, only afterdelaymilliseconds have passed with no new calls.- The wrapper must preserve the caller's
this.
The same tool powers autosave (save 500ms after the user stops editing), resize/scroll handlers, and any "wait for the dust to settle" behaviour.
Input
Use this local search mock to try the debounce function in the browser playground. It works without a backend or network access.
// Local mock data: no API URL or network request is needed.
const mockCourses = ["React", "React Native", "Redux", "JavaScript"];
let searchCalls = 0;
let results = [];
function mockSearch(query) {
searchCalls++;
return mockCourses.filter(course =>
course.toLowerCase().startsWith(query.toLowerCase())
);
}
const search = debounce((query) => {
results = mockSearch(query);
}, 100);
search("r");
search("re");
search("rea");
search("react");
setTimeout(() => {
console.log(searchCalls); // 1
console.log(results); // ["React", "React Native"]
}, 150);
Expected output
searchCalls === 1(a single mock search, not four)- That call uses the latest query,
"react" resultscontains["React", "React Native"]after the quiet period
Implement from scratch:
function debounce(fn, delay) {
// Your code here
}