JAVASCRIPT

Polling an API for Updates

Implement an API polling mechanism in JavaScript to periodically check an endpoint for updates, useful for displaying real-time-ish data or long-running task status.

function startPolling(apiEndpoint, intervalMs = 5000, maxAttempts = 0) {
  let attempts = 0;
  let timerId = null;

  const poll = async () => {
    if (maxAttempts > 0 && attempts >= maxAttempts) {
      console.log(`Polling for ${apiEndpoint} stopped after ${maxAttempts} attempts.`);
      stopPolling();
      return;
    }

    attempts++;
    console.log(`Polling ${apiEndpoint}, attempt ${attempts}...`);

    try {
      const response = await fetch(apiEndpoint);
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const data = await response.json();
      // Process the received data
      console.log('Received polled data:', data);

      // Example: If data indicates completion, stop polling
      // if (data.status === 'completed') {
      //   console.log('Polling complete, task finished.');
      //   stopPolling();
      // }

    } catch (error) {
      console.error('Polling error:', error);
      // Optionally, stop polling on persistent errors
      // stopPolling();
    }

    timerId = setTimeout(poll, intervalMs);
  };

  const stopPolling = () => {
    clearTimeout(timerId);
    console.log(`Polling for ${apiEndpoint} has been stopped.`);
  };

  // Start the first poll immediately
  timerId = setTimeout(poll, 0);

  return stopPolling; // Return the stop function to control polling externally
}

// Usage example:
// const stopDataPolling = startPolling('https://api.example.com/status/job123', 3000, 10); // Poll every 3 seconds, max 10 times
//
// // Stop polling after a certain event or time (e.g., 30 seconds)
// setTimeout(() => {
//   stopDataPolling();
// }, 30000);

// Or poll indefinitely until a condition is met in the data
// let stopUpdatesPolling = startPolling('https://api.example.com/notifications', 5000);
// // Assume 'stopUpdatesPolling' will be called when user logs out or closes a component.
How it works: This snippet provides a robust `startPolling` function to periodically fetch data from an API endpoint. It uses `setTimeout` to schedule subsequent requests after a specified `intervalMs`. The function also supports a `maxAttempts` parameter to limit the total number of polls, preventing infinite loops. A `stopPolling` function is returned, allowing external control to halt the polling process. This pattern is ideal for use cases requiring near-real-time data updates, such as tracking job statuses, notifications, or displaying dynamic content that doesn't warrant a full WebSocket connection.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs