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');Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
A local model serves few requests at a time. A search box or autocomplete that fires one per keystroke fills the queue with questions nobody cares about any more, and the answer that does matter arrives late. Waiting until the person stops typing is the cheapest measure there is against that, and it goes in the browser, before the server is touched. It works just as well for a send button pressed twice. What a small server takes with several users is measured in Ollama vs vLLM for 1 to 10 users.
Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →