Skip to content

Instantly share code, notes, and snippets.

@DarkSeraphim
Last active April 16, 2018 16:05
Show Gist options
  • Save DarkSeraphim/b6b85cb96ba21589f8c724b63cb81ec3 to your computer and use it in GitHub Desktop.
Save DarkSeraphim/b6b85cb96ba21589f8c724b63cb81ec3 to your computer and use it in GitHub Desktop.
class Interruptable {
constructor() {
this.cancelled = false;
}
cancel() {
this.cancelled = true;
if (this._timer) {
clearTimeout(this._timer);
if (!this._reject) {
throw new Exception('_reject not set');
}
this._reject();
}
}
get promise() {
return this._promise;
}
sleep(duration) {
this.timerHolder = {};
return this._promise = new Promise((resolve, reject) => {
if (this.cancelled) {
return reject();
}
this._reject = reject;
this._timer = setTimeout(() => {
if (this.cancelled) {
reject();
} else {
resolve();
}
}, duration);
});
}
}
module.exports = Interruptable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment