Created
September 11, 2017 14:48
-
-
Save mkozhukharenko/b6c4a2f6b19ab3994839fa3e5eea5906 to your computer and use it in GitHub Desktop.
Run function only when the condition is met
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
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