Skip to content

Instantly share code, notes, and snippets.

@zhangzhibin
Created September 24, 2021 01:31
Show Gist options
  • Save zhangzhibin/dfd192da8c2db6964ee901a642bacaa1 to your computer and use it in GitHub Desktop.
Save zhangzhibin/dfd192da8c2db6964ee901a642bacaa1 to your computer and use it in GitHub Desktop.
javascript/typescript wait until condition meet
// TypeScript/JavaScript 异步等待方法的实现
// refer to https://xmanyou.com/javascript-wait-until-condition-meet-or-timeout/
function waitUntil(condition:()=>boolean, timeout?:number, interval?:number) {
if (timeout === void 0) { timeout = 0; } // if not set, wait forever
if (interval === void 0) { interval = 50; } // default interval = 50ms
let waitHandler;
let timeoutHandler;
return new Promise<void>(function (resolve, reject) {
var waitFn = function () {
if (condition()) {
if(timeoutHandler){
clearTimeout(timeoutHandler);
}
resolve();
}
else {
waitHandler = setTimeout(waitFn, interval);
}
};
//
waitHandler = setTimeout(waitFn, interval);
// timeout, if timeout <=0, never timeout
if(timeout>0){
timeoutHandler = setTimeout(()=>{
if(waitHandler){
clearTimeout(waitHandler);
}
reject({
code:"TIMEOUT",
message: "timeout"
});
}, timeout);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment