JAVASCRIPT
JavaScript API Polling with Interval Control
Implement controlled API polling in JavaScript to periodically check for new data or updates from an API endpoint, with options to start, stop, and configure the polling interval.
/**
* Creates a controllable API polling mechanism.
* @param {function(): Promise<any>} fetchCallback - An async function that performs the API fetch and returns data.
* @param {number} intervalMs - The polling interval in milliseconds.
* @param {function(any): void} successCallback - Callback function for successful data fetches.
* @param {function(Error): void} errorCallback - Callback function for fetch errors.
* @returns {{start: Function, stop: Function, isRunning: Function, setInterval: Function}} Controls for the polling.
*/
function createApiPolling(fetchCallback, intervalMs, successCallback, errorCallback) {
let intervalId = null;
let currentIntervalMs = intervalMs;
let running = false;
const poll = async () => {
try {
const data = await fetchCallback();
successCallback(data);
} catch (error) {
errorCallback(error);
}
};
const start = () => {
if (!running) {
running = true;
// Run immediately once, then start interval
poll();
intervalId = setInterval(poll, currentIntervalMs);
console.log(`API polling started with interval: ${currentIntervalMs}ms`);
}
};
const stop = () => {
if (running) {
clearInterval(intervalId);
intervalId = null;
running = false;
console.log('API polling stopped.');
}
};
const setInterval = (newIntervalMs) => {
if (newIntervalMs <= 0) {
console.warn('Polling interval must be greater than 0ms.');
return;
}
currentIntervalMs = newIntervalMs;
if (running) {
stop();
start(); // Restart with new interval
}
console.log(`Polling interval updated to: ${currentIntervalMs}ms`);
};
const isRunning = () => running;
return { start, stop, isRunning, setInterval };
}
// Example Usage:
// Simulate an API call that sometimes fails
// let callCount = 0;
// const mockApiFetch = async () => {
// callCount++;
// console.log(`Mock API call #${callCount}...`);
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// if (Math.random() > 0.2) { // 80% success rate
// resolve({ status: 'ok', timestamp: new Date().toISOString(), value: Math.random() * 100 });
// } else {
// reject(new Error('Mock API error: Could not fetch data.'));
// }
// }, 500); // Simulate network latency
// });
// };
// const handleSuccess = (data) => console.log('Polling success:', data);
// const handleError = (error) => console.error('Polling error:', error.message);
// const poller = createApiPolling(mockApiFetch, 3000, handleSuccess, handleError);
// // Start polling after 1 second
// setTimeout(() => {
// poller.start();
// }, 1000);
// // Change interval after 10 seconds
// setTimeout(() => {
// poller.setInterval(1500);
// }, 10000);
// // Stop polling after 20 seconds
// setTimeout(() => {
// poller.stop();
// }, 20000);
How it works: This snippet provides a flexible JavaScript utility for API polling. The `createApiPolling` function takes a callback for the actual API fetch, an interval, and callbacks for success and error handling. It returns an object with `start`, `stop`, `isRunning`, and `setInterval` methods, allowing fine-grained control over the polling process. This pattern is useful for fetching regularly updated data, like real-time dashboards or notifications, when push mechanisms (like WebSockets) are not available or are overkill for the application's needs.