11. Debounce
Lesson 11: Debounce
In the previous lesson, you throttled updates on the server. Debouncing is the client-side counterpart - it waits until the user stops typing before sending the request.
How debounce works
Every time the input fires, cancel the previous timer and start a new one. The RPC only fires when the timer expires - meaning the user paused.
let timer;
function handleInput(e) {
clearTimeout(timer);
timer = setTimeout(async () => {
await search(e.target.value);
}, 300);
} Throttle vs debounce
- Throttle (lesson 10) - server-side, fires at most once per interval, good for continuous streams like mouse position
- Debounce (this lesson) - client-side, fires once after a pause, good for search inputs and form validation
Try it
The starter code calls the search RPC on every keystroke. Type "strawberry" and watch the "Server calls" counter hit 10. Your task:
- Add a
timervariable to hold the timeout ID - In
handleInput, callclearTimeout(timer)to cancel any pending search - Set
timer = setTimeout(() => { ... }, 300)to delay the RPC call by 300ms - Move the
search()call inside the timeout callback
Now type "strawberry" again - the counter should only go up by 1 or 2 instead of 10, because the debounce waits for you to stop typing.
WebSocket
0
No messages yet