JAVASCRIPT

Implementing API Polling for Real-time Data Updates

Discover how to implement API polling in JavaScript to periodically fetch data from a server, providing a simple way to get near real-time updates for your web application.

function startApiPolling(url, intervalMs, callback, errorCallback) {
    let pollIntervalId = null;

    const fetchData = async () => {
        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('API polling failed:', error.message);
            if (errorCallback) {
                errorCallback(error);
            }
        }
    };

    fetchData();
    pollIntervalId = setInterval(fetchData, intervalMs);

    return () => {
        clearInterval(pollIntervalId);
        console.log(`Polling stopped for ${url}`);
    };
}

// Example Usage:
// const stopPollingUpdates = startApiPolling(
//   'https://api.example.com/status',
//   5000, // Poll every 5 seconds
//   (statusData) => {
//     console.log('Current status:', statusData);
//     if (statusData.isComplete) {
//       stopPollingUpdates(); // Stop polling when a condition is met
//       console.log('Process complete, polling stopped.');
//     }
//   },
//   (error) => {
//     console.error('Error during status polling:', error.message);
//   }
// );

// To stop polling manually after some time (e.g., 30 seconds):
// setTimeout(() => {
//   stopPollingUpdates();
// }, 30000);
How it works: This JavaScript snippet provides a reusable function for implementing API polling. It periodically fetches data from a specified URL at a given interval, calling a success callback with the fetched data or an error callback if the request fails. It also returns a function that can be called to stop the polling, preventing memory leaks and unnecessary network requests when the data is no longer needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs