Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active January 11, 2019 16:41
Show Gist options
  • Save mattlockyer/82f5a28df3831e80d9a49b4cb6360ad9 to your computer and use it in GitHub Desktop.
Save mattlockyer/82f5a28df3831e80d9a49b4cb6360ad9 to your computer and use it in GitHub Desktop.
Wait for function to return true uses promise for async / await
/**************************************
* Wait for function to return true, default 50ms for 100 attempts (5s)
**************************************/
export const wait = (func, del = 50, lim = 100) => new Promise((resolve, reject) => {
let attempt = 0
const test = () => {
if (func()) resolve()
else if (attempt < lim) setTimeout(test, del)
else reject("ran out of attempts")
console.log('wait attempt', attempt)
attempt++
}
test()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment