JavaScript Snippet

Poll Until a Condition Is True

Difficulty: Medium

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.

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

183 views

2

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.