Last active
August 31, 2022 17:52
-
-
Save dr-skot/89f758d3fc61f323accb0bfa71046dd7 to your computer and use it in GitHub Desktop.
javascript: wait until a condition becomes true
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
export function waitUntil<T>(condition: () => T, timeout = 10000, interval = 50): Promise<T> { | |
let result = condition(); | |
if (result) return Promise.resolve(result); | |
return new Promise((resolve) => { | |
const finish = () => { | |
clearInterval(intervalId); | |
resolve(result); | |
}; | |
const intervalId = setInterval(() => { | |
result = condition(); | |
if (result) finish(); | |
}, interval); | |
setTimeout(finish, timeout); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment