JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Prev

Learn the concept

Promises & Async/Await

javascript
mid
async

How do you implement data polling in JavaScript?

polling
setInterval
setTimeout
async
real-time
api
abort-controller
Quick Answer

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.

Detailed Explanation

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.

Code Examples

Recursive setTimeout polling (recommended)JavaScript
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();

Real-World Applications

Use Cases

Order Tracking

Food delivery apps poll the server every few seconds to show live order status updates until the order is delivered.

Build Status Dashboard

CI/CD dashboards poll for build completion status, switching to longer intervals when builds are idle.

Mini Projects

Live Stock Ticker

intermediate

Build a stock price display that polls an API every 5 seconds with exponential backoff on failures.

Polling vs WebSocket Comparison

intermediate

Implement the same real-time feature with both polling and WebSockets, comparing network traffic and latency.

Industry Examples

Zomato

Zomato uses short polling as a fallback for order tracking when WebSocket connections cannot be established.

GitHub

GitHub Actions UI polls for workflow run status updates, showing real-time build progress without WebSockets.

Resources

MDN - AbortController

docs

MDN - setTimeout

docs

Related Questions

How do WebSockets work and when would you use them over HTTP?

senior
runtime

What are Promises in JavaScript and how do they work?

mid
async

How do async/await work and how do they relate to Promises?

mid
async
Previous
Explain event bubbling, capturing, and how stopPropagation works.
Prev