setTimeOut
What is setTimeOut
setTimeOut
waits for given ms
before calling the callback function passed to it.
Executes a function or specified piece of code once the timer expires.
- for repeated execution, use
setInterval
.
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 );