Debounce: do not call the model on every keystroke
An autocomplete that sends a prompt per keystroke saturates the server. Wait until the user stops typing.
Write debounce(fn, ms). It returns a new function that, every time it is called, restarts a timer of ms milliseconds. Only when ms pass with no new calls does fn run, once, with the arguments of the last call.
You already have wait(ms), which returns a promise that resolves after ms milliseconds.
Challenges 0/4
- A burst of calls runs fn only once
- Uses the arguments of the last call
- Does not run before the time has passed
- Two separate bursts run fn twice
function debounce(fn, ms) {
// clear the previous timer and start a new one on every call
return (...args) => fn(...args);
}
const suggest = debounce((text) => console.log('prompt:', text), 20);
suggest('h');
suggest('ho');
suggest('hola');Console output appears here (console.log).
Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →