Created
June 1, 2018 01:16
-
-
Save neofreko/a22a6c5096e49aa7864b22bdcb0b5334 to your computer and use it in GitHub Desktop.
wait until condition becomes truthy. Inspired by former works or wait-until libraries and tutorials.
This file contains hidden or 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