JavaScript

Long Polling Helper

by @admin
12h ago
Apr 28, 2026
Public
Implements a long-polling loop that repeatedly calls a fetch endpoint and invokes a callback with the result. Backs off exponentially on errors and stops cleanly when cancelled via the returned stop function. A simple alternative to WebSockets for low-frequency server-push events without SSE support.
JavaScript
function longPoll(url, onData, { interval = 3000, maxBackoff = 30_000 } = {}) {
  let delay   = interval;
  let stopped = false;

  async function poll() {
    if (stopped) return;
    try {
      const res = await fetch(url);
      if (res.ok) {
        onData(await res.json());
        delay = interval;
      }
    } catch (err) {
      console.warn('Long poll error:', err);
      delay = Math.min(delay * 2, maxBackoff);
    }
    if (!stopped) setTimeout(poll, delay);
  }

  poll();
  return { stop: () => { stopped = true; } };
}

// Usage
const poller = longPoll('/api/notifications', (data) => {
  console.log('New notification:', data);
});

// Later: poller.stop();
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.