JAVASCRIPT

Polling an API for Status Updates

Implement a robust client-side polling mechanism to periodically check an API endpoint for updated status or data, useful for long-running background tasks.

function startPolling(url, intervalMs, callback, errorCallback) {
  let intervalId;
  let stopPollingFlag = false; // Flag to control stopping from outside

  const poll = async () => {
    if (stopPollingFlag) {
      clearInterval(intervalId);
      return;
    }
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const data = await response.json();
      callback(data);
    } catch (error) {
      console.error('Polling error:', error);
      if (errorCallback) {
        errorCallback(error);
      }
      // Optionally stop polling on critical errors
      // stopPollingFlag = true;
      // clearInterval(intervalId);
    }
  };

  intervalId = setInterval(poll, intervalMs);
  console.log(`Polling started for ${url} every ${intervalMs}ms.`);

  return () => {
    stopPollingFlag = true; // Set flag to stop the next iteration
    console.log(`Polling stopped for ${url}.`);
  };
}

// Example Usage:
// let stopPollingOrders;
//
// const handleOrderUpdate = (data) => {
//   console.log('Order status updated:', data);
//   if (data.status === 'completed' || data.status === 'failed') {
//     stopPollingOrders(); // Stop polling when the order reaches a final state
//   }
// };
//
// const handleError = (error) => {
//   console.error('Failed to poll order status:', error);
// };
//
// // Start polling every 5 seconds (5000ms)
// stopPollingOrders = startPolling(
//   'https://api.example.com/orders/123/status',
//   5000,
//   handleOrderUpdate,
//   handleError
// );
//
// // To manually stop after some time or event:
// // setTimeout(() => {
// //   if (stopPollingOrders) stopPollingOrders();
// // }, 30000); // Stop after 30 seconds if not already stopped
How it works: This JavaScript snippet provides a simple mechanism for polling an API endpoint at regular intervals. The `startPolling` function sets up a `setInterval` that repeatedly fetches data from the specified URL. A `callback` function is invoked with the fetched data, allowing the application to react to updates. An optional `errorCallback` handles issues during the fetch. It returns a cleanup function to explicitly stop polling, preventing memory leaks and unnecessary network requests when the polling is no longer needed. This is useful for tracking the status of asynchronous background tasks or real-time data 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