Debounce the Search
25 minIntermediateJavaScript
Right now every keystroke runs a search. Type nasi and renderResults runs four times (n, na, nas, nasi). If each search were a request to a server, that's three wasted requests per word. Open the console and watch it happen.
Debouncing fixes this: wait until the user pauses, then run once with the final value.
const log = debounce((x) => console.log(x), 300);
log("a"); log("b"); log("c");
// ...300 ms of silence...
// logs "c" onceHow debounce should behave
Requirements
debounce(fn, delay)returns a new function. Each call restarts the timer;fnruns once,delayms after the last call, with the last call's arguments.- Calls that are further apart than
delayeach runfnseparately. - Wire the search box with a 300 ms debounce. Don't change
renderResults.
Implement debounce(fn, delay) and use it so the search box calls renderResults only once, 300 ms after the user stops typing, with the latest text.
Checks
- Runs once, after the last call, with the last arguments
- Separate pauses run separately, with all arguments
- The search box waits until typing stops
Preview
Console output from your code appears here.