Poll for New Messages Without Overlapping Browser Requests

Last updated: November 28, 2026.

On a host that handles short HTTP requests, poll a small endpoint for rows newer than the last message you rendered. Start each wait after the request completes, and skip requests while the page is hidden.

let after = '';
let delay = 2000;
const messages = document.querySelector('#messages');

async function poll() {
  if (document.visibilityState === 'visible') {
    try {
      const query = new URLSearchParams({ after });
      const response = await fetch('/messages?' + query, {
        signal: AbortSignal.timeout(8000),
        cache: 'no-store'
      });
      if (!response.ok) throw new Error('HTTP ' + response.status);
      const { rows, next } = await response.json();

      for (const row of rows) {
        const item = document.createElement('li');
        item.textContent = row.text;
        messages.append(item);
      }
      after = next;
      delay = rows.length ? 2000 : Math.min(delay * 2, 15000);
    } catch (error) {
      console.warn('Message polling failed', error);
      delay = Math.min(delay * 2, 15000);
    }
  }
  setTimeout(poll, delay);
}

poll();

Define the endpoint contract

Place an element with ID messages in the page and load the script after it. The signed-in endpoint returns an object with rows in display order and a string cursor named next. An empty result should preserve the cursor. Choose a stable ordering, cap the number of rows per reply and authorize the conversation on each request. If a full batch indicates a backlog, fetch subsequent batches at a pace your service can support.

Tune the delay with production traffic

An active page polls every two seconds plus request time. An idle or failing endpoint brings the delay up to fifteen seconds. A hidden tab checks the timer without starting another request. It may wait until its next scheduled check after becoming visible again. Add jitter if many clients are likely to retry together, and honor rate-limit responses in a production client. Stop polling if the user must sign in again.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov