Skip to content

Instantly share code, notes, and snippets.

@CodeLenny
Created August 21, 2017 18:25
Show Gist options
  • Save CodeLenny/a5025b03896b6a4554fd609517559234 to your computer and use it in GitHub Desktop.
Save CodeLenny/a5025b03896b6a4554fd609517559234 to your computer and use it in GitHub Desktop.
<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