wait until condition becomes truthy. Inspired by former works or wait-until libraries and tutorials.
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
const waitUntil = async (asyncCondition, timeoutMs) => { | |
const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
const intervalMs = 1000; | |
const startTime = Date.now(); | |
const result = await asyncCondition(); | |
const endTime = Date.now(); | |
const timeSpentMs = endTime - startTime; | |
console.log(`checking waitUntil condition, timeout in: ${timeoutMs}ms`); | |
if (result) return result; | |
if (timeoutMs - timeSpentMs - intervalMs < 0) return result; | |
await wait(intervalMs); | |
return await waitUntil(asyncCondition, timeoutMs - timeSpentMs - intervalMs); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment