Skip to content

Instantly share code, notes, and snippets.

@mkozhukharenko
Created September 11, 2017 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkozhukharenko/b6c4a2f6b19ab3994839fa3e5eea5906 to your computer and use it in GitHub Desktop.
Save mkozhukharenko/b6c4a2f6b19ab3994839fa3e5eea5906 to your computer and use it in GitHub Desktop.
Run function only when the condition is met
interface IWaitForArgs {
test: () => boolean // run function only if test() returns true
interval: number
count: number // should be 0, required
maxAttempts: number // max number of attempts
run: () => any // function to run
}
function waitFor({test, interval, count, maxAttempts, run}: IWaitForArgs) {
// try to run function only maxAttempts times
if (maxAttempts === count) {
return
}
// Check if condition met. If not, re-check later.
while (test() !== true) {
count++
setTimeout(() => {
waitFor({test, interval, count, maxAttempts, run})
}, interval)
return
}
// Condition finally met. run() can be executed.
run()
}
export default waitFor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment