Learn the concept
Promises & Async/Await
Data polling repeatedly fetches data at fixed intervals using setInterval or recursive setTimeout. Recursive setTimeout is preferred because it waits for the previous request to complete before scheduling the next one, preventing request pile-up on slow networks.
What is Polling?
Polling is the technique of periodically requesting data from a server at fixed intervals. It is the simplest way to keep a client's data in sync with the server when real-time push mechanisms (WebSockets, Server-Sent Events) are not available or practical.
setInterval vs Recursive setTimeout:
setInterval fires at fixed intervals regardless of whether the previous request has completed. If a request takes 3 seconds but the interval is 2 seconds, requests pile up and overlap — leading to race conditions and wasted bandwidth.
Recursive setTimeout waits for the current operation to finish, then schedules the next one after the delay. This guarantees sequential execution with a minimum gap between requests.
Exponential Backoff:
When requests fail (server errors, network issues), hammering the server with rapid retries makes things worse. Exponential backoff increases the delay after each failure (e.g., 1s → 2s → 4s → 8s up to a maximum), then resets when a request succeeds.
Cleanup and Cancellation:
Polling must be stopped when the component unmounts or the user navigates away. In React, this means clearing the timeout in the useEffect cleanup function. For in-flight requests, AbortController cancels pending fetches to prevent state updates on unmounted components.
When to Use Polling vs Alternatives:
| Approach | Use When | |----------|----------| | Short polling | Simple use case, updates every 5-30 seconds | | Long polling | Need near-real-time but can't use WebSockets | | Server-Sent Events | Server-to-client only, simple protocol | | WebSockets | Bidirectional real-time communication |
Long Polling:
Long polling keeps the HTTP request open until the server has new data or a timeout occurs. The client immediately reconnects after receiving a response. This provides near-real-time updates over standard HTTP without the overhead of rapid repeated requests.
async function pollData(url, interval = 5000) {
const controller = new AbortController();
async function poll() {
try {
const response = await fetch(url, { signal: controller.signal });
const data = await response.json();
console.log('Received:', data);
// Schedule next poll AFTER this one completes
setTimeout(poll, interval);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Polling stopped');
return;
}
console.error('Poll failed:', error);
// Still schedule next attempt on error
setTimeout(poll, interval);
}
}
poll(); // Start polling
// Return cleanup function
return () => controller.abort();
}
// Usage
const stopPolling = pollData('/api/orders/status');
// Later: stopPolling();Food delivery apps poll the server every few seconds to show live order status updates until the order is delivered.
CI/CD dashboards poll for build completion status, switching to longer intervals when builds are idle.
Build a stock price display that polls an API every 5 seconds with exponential backoff on failures.
Implement the same real-time feature with both polling and WebSockets, comparing network traffic and latency.