The Classic Fallback
Long Polling is the oldest method to simulate " real-time " updates. It's still used as a fallback when WebSockets and SSE are blocked (e.g., by strict corporate firewalls).
How It Works
- Browser sends a request to the server.
- Server does NOT respond immediately — it holds the connection open until it has new data.
- When new data arrives, the server responds.
- Browser receives the response and immediately sends a new request.
- Repeat.
async function subscribe() {
try {
const response = await fetch('/api/subscribe', {
signal: AbortSignal.timeout(30_000) // 30 second timeout
});
if (response.status === 200) {
const message = await response.json();
handleNewMessage(message);
}
} catch (error) {
if (error.name !== 'TimeoutError') {
// Real error — wait before retrying
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
// Always schedule next poll
subscribe();
}
subscribe(); // Start the loop
Tip
Use long polling only when your users are behind strict corporate firewalls that block WebSockets. For all other cases, WebSocket or SSE are significantly better.