Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
All three technologies are ways to get data from server in browser. They allow updating client in real or near real-time, especially when WebSockets aren't available.
Client periodically polls server: "Anything new?"
GET /datasetInterval(() => {
fetch('/data')
.then(res => res.json())
.then(data => console.log(data));
}, 5000); // Request every 5 sec
Improved version of regular polling: request lives until new data appears.
function longPolling() {
fetch('/data')
.then(res => res.json())
.then(data => {
console.log(data);
longPolling(); // Loop continues
});
}
longPolling();
SSE is persistent connection through which server sends data to client when it wants.
This is unidirectional connection: server → client only
EventSourcetext/event-streamconst eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log("New message:", event.data);
};
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
setInterval(() => {
res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
}, 3000);
});
| Method | Direction | Persistent Connection | Instantness | Complexity | Support |
|---|---|---|---|---|---|
| Polling | Client → Server | No | No | Simple | All |
| Long Polling | Client → Server | Temporary | Almost | Medium | All |
| SSE | Server → Client | Yes | Yes | Medium | Almost all (except IE) |
Conclusion:
Polling is simple but inefficient. Long Polling is compromise. SSE is excellent solution for real-time without using WebSocket. Choice depends on communication direction, load, latency requirements and browser support.