JAVASCRIPT
Efficient API Polling for Real-time Data Updates
Implement effective API polling to regularly fetch and update data in your web application, complete with proper cleanup to prevent memory leaks and ensure optimal performance.
function setupApiPolling(apiUrl, intervalMs, callback, onError = console.error) {
let pollTimer = null;
let isPollingActive = false;
const fetchData = async () => {
if (!isPollingActive) return; // Prevent fetching if polling was stopped
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
callback(data); // Pass data to the provided callback function
} catch (error) {
onError(error); // Handle errors with the provided error handler
}
};
const startPolling = () => {
if (isPollingActive) return; // Already polling
isPollingActive = true;
fetchData(); // Initial fetch immediately
pollTimer = setInterval(fetchData, intervalMs);
console.log(`Polling started for ${apiUrl} every ${intervalMs}ms.`);
};
const stopPolling = () => {
if (!isPollingActive) return; // Not polling
isPollingActive = false;
clearInterval(pollTimer);
console.log(`Polling stopped for ${apiUrl}.`);
};
return { startPolling, stopPolling };
}
// Example Usage (e.g., in a React component's useEffect or a plain JS app):
// const apiUrl = 'https://api.example.com/live-status';
// const pollInterval = 5000; // 5 seconds
// const updateUI = (data) => {
// console.log('Live data received:', data);
// // Update your UI here
// document.getElementById('status-display').textContent = JSON.stringify(data);
// };
// const { startPolling, stopPolling } = setupApiPolling(apiUrl, pollInterval, updateUI);
// // To start:
// startPolling();
// // To stop (e.g., when component unmounts or user navigates away):
// // setTimeout(stopPolling, 30000); // Stop after 30 seconds for example
How it works: This snippet provides a reusable function for polling an API at a regular interval to fetch "real-time" updates. It sets up an `setInterval` to repeatedly call the API and executes a callback with the fetched data. Crucially, it includes `startPolling` and `stopPolling` methods to manage the interval, ensuring proper cleanup (using `clearInterval`) to prevent memory leaks or unnecessary network requests when the polling is no longer needed.