Created
July 10, 2021 08:39
-
-
Save yunusga/ca2968bfa22bd13d11c7a9c56dbdeac4 to your computer and use it in GitHub Desktop.
Wait some async scripts
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
/** | |
* Wait some async stuff | |
* | |
* usage | |
let waitStuff = new Waiter('tns', 'function', () => { // callback }).check(); | |
*/ | |
class Waiter { | |
constructor(what, type, callback, timeout = 100, attempts = 50, from = window) { | |
this.what = what; | |
this.type = type; | |
this.callback = callback; | |
this.timeout = timeout; | |
this.attempts = attempts; | |
this.count = 0; | |
this.from = from; | |
} | |
check() { | |
if (this.count >= this.attempts) { | |
return; | |
} | |
this.count++; | |
if (typeof this.from[this.what] === this.type) { | |
this.callback(); | |
} else { | |
setTimeout(() => { | |
this.check(); | |
}, 100); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment