Skip to content

Instantly share code, notes, and snippets.

@koohq
Last active January 8, 2018 13:12
Show Gist options
  • Save koohq/f484b0d4b135656884246b0bd54d66f8 to your computer and use it in GitHub Desktop.
Save koohq/f484b0d4b135656884246b0bd54d66f8 to your computer and use it in GitHub Desktop.
Provides waiting method for unfriendly async process (ex. no notify completion)
/**
* wait.js
*
* (c) 2018 koohq. Licensed under CC0.
* https://creativecommons.org/publicdomain/zero/1.0/legalcode
*/
var Wait = (function() {
function Wait(timeout, interval) {
this.timeout = timeout;
this.interval = interval;
}
var defaultTimeout = 1000;
var defaultInterval = 10;
Wait.prototype.until = function(condition) {
return new Promise(function(resolve, reject) {
if (condition()) { resolve(); return; }
var interval = this.interval > 0 ? this.interval : defaultInterval;
var timeout = this.timeout > 0 ? this.timeout : defaultTimeout;
var limit = Math.ceil(timeout / interval);
var count = 0;
var intervalID = setInterval(function() {
if (condition()) {
clearInterval(intervalID);
resolve();
} else if(count >= limit) {
clearInterval(intervalID);
reject();
}
count++;
}, interval);
});
};
return Wait;
})();
/**
* wait.usage.js
*
* (c) 2018 koohq. Licensed under CC0.
* https://creativecommons.org/publicdomain/zero/1.0/legalcode
*/
// configure Wait
var timeoutMilliSeconds = 3000;
var intervalMilliSeconds = 100;
var wait = new Wait(timeoutMilliSeconds, intervalMilliSeconds);
// 'isReady' will be true sometime soon.
var isReady = false;
(function oneAsyncProcess() { setTimeout(function() { isReady = true; }, 1000); })();
// wait until 'isReady to be true'...
wait.until(function() { return isReady; })
.then(function() { console.log('OK'); })
.catch(function() { console.error('NG'); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment