Last active
August 22, 2023 17:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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