JAVASCRIPT
Periodic API Data Fetching with Polling
Implement effective API polling in JavaScript to periodically fetch and update data, ideal for near real-time updates without WebSockets.
class ApiPoller {
constructor(url, intervalMs, callback) {
this.url = url;
this.intervalMs = intervalMs;
this.callback = callback;
this.timerId = null;
this.isPolling = false;
}
async poll() {
if (!this.isPolling) return; // Stop if polling was stopped externally
try {
const response = await fetch(this.url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
this.callback(null, data); // Pass null for error, data for success
} catch (error) {
console.error('Polling error:', error);
this.callback(error, null); // Pass error, null for data
} finally {
// Schedule the next poll, but only if still active
if (this.isPolling) {
this.timerId = setTimeout(() => this.poll(), this.intervalMs);
}
}
}
start() {
if (this.isPolling) {
console.warn('Poller already running.');
return;
}
this.isPolling = true;
console.log(`Starting polling for ${this.url} every ${this.intervalMs / 1000} seconds.`);
this.poll(); // Initial immediate poll
}
stop() {
this.isPolling = false;
if (this.timerId) {
clearTimeout(this.timerId);
this.timerId = null;
}
console.log(`Stopped polling for ${this.url}.`);
}
}
// Example Usage:
// const dataUpdateCallback = (error, data) => {
// if (error) {
// document.getElementById('status').textContent = `Error: ${error.message}`;
// } else {
// document.getElementById('data-display').textContent = JSON.stringify(data, null, 2);
// document.getElementById('status').textContent = `Last updated: ${new Date().toLocaleTimeString()}`;
// }
// };
// const myPoller = new ApiPoller('https://api.example.com/live-data', 5000, dataUpdateCallback);
// // To start polling:
// // myPoller.start();
// // To stop polling after some time or event:
// // setTimeout(() => myPoller.stop(), 30000); // Stop after 30 seconds
How it works: This snippet demonstrates an API polling mechanism using a JavaScript class. Polling involves making repeated requests to an API endpoint at fixed intervals to retrieve updated data. This pattern is useful for situations where near real-time updates are needed but WebSockets might be overkill or not supported by the API. The `ApiPoller` class provides `start` and `stop` methods to manage the polling cycle, ensuring that requests are only made when active and that the timer is properly cleared to prevent memory leaks or unintended behavior. It also includes basic error handling and uses `setTimeout` for staggered requests, rather than `setInterval`, to ensure that each subsequent request waits for the previous one to complete before scheduling.