Code Snippets
/

Poll Until a Condition Is True

Poll Until a Condition Is True

Polling shows up everywhere systems are eventually consistent: waiting for a job status to flip to `done`, for a file to appear, for a deploy to roll out. This snippet walks from a basic fixed-interval poller to one with a deadline, then to exponential backoff with jitter so a thundering herd does not hammer the upstream. Reach for it any time you need to wait for a remote condition without writing the same retry loop again.

JavaScript
Medium
3 snippets
async-programming
promises
utility
retry-policy

185 views

2

async function pollUntil(check, intervalMs = 100) {
    while (true) {
        const result = await check();
        if (result) return result;
        await new Promise((r) => setTimeout(r, intervalMs));
    }
}

let basicAttempt = 0;
async function basicCheck() {
    basicAttempt += 1;
    return basicAttempt >= 3 ? `ready after ${basicAttempt}` : null;
}

pollUntil(basicCheck, 5).then((v) => console.log(v));

The simplest polling loop runs check() and either returns its truthy result or sleeps for intervalMs and tries again. await keeps the loop linear and exception-safe: an error in check rejects the outer promise instead of silently retrying. Use this for fast, synchronous-feeling waits where the worst case (hung loop) is acceptable. The major footgun is no upper bound: if the condition never becomes true, the loop runs forever, which is why production code uses the timeout variant.