Skip to content

Instantly share code, notes, and snippets.

@mkhahani
Last active July 3, 2019 05:36
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 mkhahani/b9fbb998219c457bf423917f39fc56c5 to your computer and use it in GitHub Desktop.
Save mkhahani/b9fbb998219c457bf423917f39fc56c5 to your computer and use it in GitHub Desktop.
JavaScript waitFor Promise based utility function
/**
* Waits specific amount of time for a function to fulfill
* @param {number} timeout
* @param {function} check
* @return {Promise<any>}
*/
waitFor: (timeout, check) => new Promise((resolve, reject) => {
const timer = setInterval(() => {
if (check()) {
clearInterval(timer);
resolve();
}
}, 100);
setTimeout(() => {
clearInterval(timer);
reject();
}, timeout);
}),
// Usage
let variable = false;
const check = () => variable;
setTimeout(() => {
variable = true;
}, 3000);
waitFor(4000, check)
.then(() => {
console.log('success');
})
.catch(() => {
console.log('failure');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment