JAVASCRIPT

Poll an API for Real-time Status Updates

Implement client-side polling to periodically fetch status updates from an API, useful for long-running tasks or displaying real-time data on a web page.

function pollApiForStatus(endpoint, intervalMs = 3000, maxAttempts = 10) {
  let attempts = 0;
  let pollIntervalId;

  const startPolling = () => {
    pollIntervalId = setInterval(async () => {
      attempts++;
      console.log(`Polling attempt ${attempts} for ${endpoint}...`);

      try {
        const response = await fetch(endpoint);
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();

        // Check a specific status field in the response
        if (data.status === 'completed' || data.status === 'failed') {
          console.log('Polling complete, final status:', data.status, 'Data:', data);
          clearInterval(pollIntervalId); // Stop polling
          return; // Exit
        } else {
          console.log('Current status:', data.status);
        }

      } catch (error) {
        console.error('Error during polling:', error.message);
      }

      if (attempts >= maxAttempts) {
        console.warn(`Polling stopped after ${maxAttempts} attempts.`);
        clearInterval(pollIntervalId); // Stop polling after max attempts
      }
    }, intervalMs);
  };

  const stopPolling = () => {
    clearInterval(pollIntervalId);
    console.log('Polling explicitly stopped.');
  };

  startPolling(); // Start immediately

  return { stopPolling }; // Allow external control
}

// Usage example:
// // Imagine an API endpoint that returns { status: 'pending' | 'processing' | 'completed' | 'failed' }
// const pollingSession = pollApiForStatus('https://api.example.com/task-status/123', 2000, 15);
//
// // To stop polling externally after some condition or user action:
// // setTimeout(() => {
// //   pollingSession.stopPolling();
// // }, 30000); // Stop after 30 seconds if not already completed
How it works: This snippet illustrates how to implement client-side API polling using `setInterval`. It repeatedly fetches data from a specified endpoint at a given interval, useful for checking the status of long-running background tasks or for displaying frequently updated data. The polling stops either when a desired `status` is received from the API or after a maximum number of attempts, preventing infinite loops.

Need help integrating this into your project?

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

Hire DigitalCodeLabs