Skip to content

Instantly share code, notes, and snippets.

@hmmhmmhm
Created June 20, 2021 10:37
Show Gist options
  • Select an option

  • Save hmmhmmhm/1b48d2a0203d259e37b764a01616c8cf to your computer and use it in GitHub Desktop.

Select an option

Save hmmhmmhm/1b48d2a0203d259e37b764a01616c8cf to your computer and use it in GitHub Desktop.
await when condition end (typescript)
export const when = (
condition: () => boolean | Promise<boolean>,
timeoutMs = 0,
repeatMs = 500
) => {
return new Promise<void>((resolve) => {
const startTime = Date.now()
const checkFlag = async () => {
if (await condition()) {
resolve()
} else if (timeoutMs !== 0 && Date.now() > startTime + timeoutMs) {
resolve()
} else {
window.setTimeout(checkFlag, repeatMs)
}
}
checkFlag()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment