← Back to all snippets
JAVASCRIPT

Polling an API for Real-time Data Updates in JavaScript

Implement API polling in JavaScript to periodically fetch data and keep your application updated without using WebSockets. Learn to manage intervals and clear polling.

function startPolling(url, intervalMs = 5000, callback) {
    let pollIntervalId;

    async function poll() {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            callback(null, data); // Call callback with data
        } catch (error) {
            console.error('Polling error:', error);
            callback(error, null); // Call callback with error
        }
    }

    // Start initial poll immediately
    poll();

    // Then set up interval
    pollIntervalId = setInterval(poll, intervalMs);

    // Return a function to stop polling
    return () => {
        clearInterval(pollIntervalId);
        console.log('Polling stopped.');
    };
}

// Example Usage:
// const stopPolling = startPolling('https://jsonplaceholder.typicode.com/todos/1', 3000, (error, data) => {
//     if (error) {
//         console.error('Failed to get polled data:', error);
//     } else {
//         console.log('Polled Data:', data);
//     }
// });

// Stop polling after some time (e.g., 15 seconds)
// setTimeout(() => {
//     stopPolling();
// }, 15000);
How it works: This JavaScript snippet demonstrates how to implement API polling, a technique where an application periodically sends requests to an API to check for updates. This is useful for displaying near real-time data when WebSockets are not an option. The `startPolling` function takes a URL, an interval, and a callback. It immediately performs an initial fetch, then sets up an interval to repeatedly call the API. It returns a function to easily stop the polling mechanism using `clearInterval`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs