Debouncing WebSocket Events in Real-Time Apps
JavaScript WebSockets Performance Real-Time
Ever seen a “John is typing…” message in a chat app and wondered how the website knows that?
Behind the scenes, the app uses WebSockets, an open two-way connection between your browser and the server that allows messages to flow instantly in both directions.
The Problem: Too Many Messages
A fast typist can press 5 keys in one second. Without any control, the browser would send 5 separate notifications to the server for every one of those keystrokes:
Key pressed! Key pressed! Key pressed!
Multiply that by hundreds of users typing at the same time, and you have a flood of unnecessary traffic wasting server resources and slowing everything down.
The Fix: Debouncing
Debouncing is a simple technique: wait until the user pauses before doing anything.
Here’s the rule it follows:
- User presses a key → start a short timer (e.g., 1.5 seconds).
- User presses another key → reset the timer.
- User stops typing and the timer runs out → now send the update.
This turns hundreds of chaotic messages into just two clean signals: one when typing starts, one when it stops.
The Code
let typingTimer;
let isTyping = false;
function handleKeystroke() {
// Clear the previous timer on every keystroke
clearTimeout(typingTimer);
// Only notify the server once when typing begins
if (!isTyping) {
isTyping = true;
sendStatusToServer("is-typing");
}
// Wait for the user to pause, then send the stop signal
typingTimer = setTimeout(() => {
isTyping = false;
sendStatusToServer("stopped-typing");
}, 1500); // 1.5 seconds of silence
}
Note: The
isTypingflag prevents sending"is-typing"repeatedly on every single keystroke — only the first keypress triggers it.
The Result
| Without Debouncing | With Debouncing |
|---|---|
| 5 messages per second | 2 messages total |
| Server gets flooded | Server stays calm |
| UI can lag under load | UI stays responsive |
A one-line timer saves your server from hundreds of unnecessary calls — and keeps your real-time UI fast and clean.