JAVASCRIPT
Implement API Polling for Real-time Updates
Continuously fetch fresh data from an API at regular intervals, enabling near real-time updates for dashboards or status displays in web applications.
/**
* Starts polling an API endpoint at a specified interval.
* @param {string} url - The API endpoint URL to poll.
* @param {function(data: object): void} callback - Callback function to handle fetched data.
* @param {number} interval - Polling interval in milliseconds.
* @param {object} [options={}] - Fetch options for the API call.
* @returns {{ stop: () => void, start: () => void }} An object with stop and start functions.
*/
function createApiPoller(url, callback, interval = 5000, options = {}) {
let timerId = null;
let isActive = false;
const fetchData = async () => {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
callback(data);
} catch (error) {
console.error('API polling error:', error);
// Optionally, implement error handling or stop polling on persistent errors
// stop();
} finally {
if (isActive) {
timerId = setTimeout(fetchData, interval);
}
}
};
const start = () => {
if (!isActive) {
isActive = true;
console.log(`Starting API polling for ${url} every ${interval}ms.`);
// Fetch immediately on start, then start interval
fetchData();
}
};
const stop = () => {
if (isActive) {
isActive = false;
clearTimeout(timerId);
console.log(`Stopped API polling for ${url}.`);
}
};
return { start, stop };
}
// Example usage:
// const statusPoller = createApiPoller(
// 'https://api.example.com/status',
// (data) => {
// console.log('Current status:', data);
// document.getElementById('status-display').textContent = JSON.stringify(data, null, 2);
// },
// 3000 // Poll every 3 seconds
// );
// // Start polling
// statusPoller.start();
// // Stop polling after some time (e.g., 30 seconds)
// // setTimeout(() => {
// // statusPoller.stop();
// // }, 30000);
How it works: This snippet provides a `createApiPoller` function to implement API polling, a technique for continuously fetching updated data from an API at regular intervals. It returns an object with `start` and `stop` methods to control the polling lifecycle. This approach is useful for displaying near real-time information in dashboards or status updates where WebSockets might be overkill or unavailable, ensuring the UI remains fresh with the latest data. Proper cleanup with `clearTimeout` prevents memory leaks.