Created
August 21, 2017 18:25
-
-
Save CodeLenny/a5025b03896b6a4554fd609517559234 to your computer and use it in GitHub Desktop.
This file contains 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
<script> | |
/** | |
* Wait for a condition to be true before continuing. | |
* @param {Number} [delay] a timeout (in ms) for when an error should be thrown for a function that will never be true. | |
* Defaults to `2000`. | |
* @param {Function<Boolean>} fn the function to poll to determine if the program should continue. | |
* Return `true` when the Promise should resolve. | |
* @return {Promise} resolves when `fn` returns `true`. Rejects with an `EvalError` if `fn` doesn't return `true` before `delay`. | |
*/ | |
window.waitFor = function(delay, fn) { | |
if(!fn) { | |
fn = delay; | |
delay = 2000; | |
} | |
const startTime = Date.now(); | |
const timeoutError = new EvalError("waitFor function never returned 'true'."); | |
let responded = false; | |
return new Promise((resolve, reject) => { | |
let responded = false; | |
let poll; | |
function test() { | |
try { | |
if(fn() === true && responded === false) { | |
responded = true; | |
clearInterval(poll); | |
resolve(); | |
} | |
} | |
catch (err) { return; } | |
} | |
poll = setInterval(test, 10); | |
setTimeout(() => { | |
if(responded) { return; } | |
clearInterval(poll); | |
responded = true; | |
reject(timeoutError); | |
}, delay); | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment