What Is Polling?
Polling is a technique where a client repeatedly asks the server for new data at regular intervals.
- The client sends an HTTP request.
- The server responds with current data (or “no new data”).
- The client waits a fixed amount of time, then asks again.
Imagine you are eagerly awaiting a package delivery. Instead of waiting at home all day, you decide to call the delivery service every hour to inquire if your package has arrived.
OR
It is like asking your friend “Are we there yet?” during a road trip.
Short Interval (Basic Polling)
How it works:
Client sends a request to a server:
GET /messagesServer responds:
{ "messages": ["Hello", "Hi!"] }- Clients waits N seconds (e.g., 2 seconds) and sends the request again.
Example JavaScript Code:
function poll() {
fetch('/messages')
.then(response => response.json())
.then(data => {
console.log(data.messages);
setTimeout(poll, 2000); // poll every 2 seconds
});
}
poll();Key Points:
- Simple to implement
- Works with any HTTP server
- Constantly generates requests, even when no new data exists.
Long Polling (Improved Version)
It is more like asking your friend “Let me know when we reach” and then waiting patiently for their response. The client makes a request to the server, but instead of getting an immediate response, the server holds the connection open until new data is available or a timeout occurs.
Problem with basic polling:
- Lots of unnecessary requests if there's no new data.
- High latency between server updates and client.
Solution: Long Polling
- Client sends request.
- Server holds the request open until new data arrives or a timeout occurs.
- Server responds immediately when data is ready.
Long Polling Flow
- Client requests
/messages - Server checks for new messages:
- If none, wait (hold request)
- If new message, respond immediately
- Client receives data -> immediately sends another request
- Repeat
Advantages over basic polling:
- Reduces unnecessary requests
- Faster notification of new data
- Works with standard HTTP
Example JavaScript Long Polling
function longPoll() {
fetch('/messages')
.then(res => res.json())
.then(data => {
console.log(data.messages);
longPoll(); // immediately poll again
})
.catch(err => setTimeout(longPoll, 2000)); // retry on error
}
longPoll();
Leave a comment
Your email address will not be published. Required fields are marked *


