Frontend Patterns

Pattern

Polling

Fetch data repeatedly at regular intervals to keep information current.

Polling

Problem

Data becomes stale and outdated as soon as it’s displayed, requiring manual refreshes to see updates. Users monitoring dashboards, order statuses, or real-time metrics have no way to see changes without repeatedly clicking refresh. Critical updates like payment confirmations or stock levels don’t appear until users manually reload the page.

Solution

Repeatedly request fresh data at regular intervals to keep the UI synchronized with server state. This provides eventual consistency but can waste bandwidth when nothing changes.

Example

This example demonstrates polling a status endpoint every 5 seconds to keep the UI updated, with proper cleanup when the component is removed.

// Framework-agnostic polling
class StatusMonitor extends HTMLElement {
  connectedCallback() {
    // Start polling when component mounts
    this.startPolling();
  }

  disconnectedCallback() {
    // Clean up interval when component unmounts
    this.stopPolling();
  }

  startPolling() {
    // Set up interval to fetch data every 5 seconds
    this.pollInterval = setInterval(async () => {
      const response = await fetch('/api/status');
      const status = await response.json();
      // Update UI with latest data
      this.updateStatus(status);
    }, 5000); // Poll every 5 seconds
  }

  stopPolling() {
    // Clear interval to prevent memory leaks
    if (this.pollInterval) {
      clearInterval(this.pollInterval);
    }
  }

  updateStatus(status) {
    this.innerHTML = `<div>Status: ${status.value}</div>`;
  }
}

Benefits

  • Keeps UI up-to-date with server state without requiring user interaction.
  • Simple to implement without complex WebSocket or server-sent event infrastructure.
  • Works reliably across all browsers and network conditions.
  • Provides eventual consistency for data that changes frequently.

Tradeoffs

  • Wastes bandwidth by requesting data even when nothing has changed.
  • Creates unnecessary server load with constant requests.
  • Can be delayed if polling interval is too long or wasteful if too short.
  • Inferior to WebSockets or Server-Sent Events for real-time requirements.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.