Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active August 22, 2023 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/46c9dec4535da36809f4 to your computer and use it in GitHub Desktop.
Save loilo/46c9dec4535da36809f4 to your computer and use it in GitHub Desktop.
Sometimes there is 3rd party code to wait for and you can't hack into it with callbacks or promises. This script runs a check function periodically until it returns true (in which case its returned promise is resolved) or until it times out (which means it's going to reject). Inspired by a blog post by David Walsh.
/**
* Resolve a promise when a condition matches
*
* @param condition The callback to run for checking
* @param interval How frequent to check the condition (interval in milliseconds)
* @param timeout After how many milliseconds to reject the promise
*/
async function poll(condition: () => boolean, interval: number, timeout?: number): Promise<void> {
const startTime = Date.now()
while (true) {
if (typeof timeout === 'number' && Date.now() > startTime + timeout) {
throw new Error('Condition not met before timeout')
}
const result = await condition()
if (result) return
await new Promise(resolve => setTimeout(resolve, interval))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment