Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Last active August 31, 2022 17:52
Show Gist options
  • Save dr-skot/89f758d3fc61f323accb0bfa71046dd7 to your computer and use it in GitHub Desktop.
Save dr-skot/89f758d3fc61f323accb0bfa71046dd7 to your computer and use it in GitHub Desktop.
javascript: wait until a condition becomes true
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