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
let requests = 0;
const search = debounce((query) => {
requests++;
fetch(`/api/search?q=${query}`);
}, 100);
search("r");
search("re");
search("rea");
search("react");
// user stops typing; wait > 100ms
Expected output
requests === 1(a single call, not four)- That call uses the latest query,
"react"
Implement from scratch:
function debounce(fn, delay) {
// Your code here
}