Usage in polling
function poll(callback, interval, timeout) {
let endTime = Date.now() + timeout;
let checkCondition = function() {
if (callback()) {
// Success condition met
return;
} else if (Date.now() < endTime) {
// Try again after interval
setTimeout(checkCondition, interval);
} else {
// Timeout reached
console.error('Polling timeout');
}
};
checkCondition();
}
poll(
() => {
return fetch('/api/data')
.then(res => res.json())
.then(data => data.status === 'complete');
},
1000, // 1-second interval
5000 // 5-second timeout
);