Skip to content

Instantly share code, notes, and snippets.

@sethwebster
Created November 15, 2018 14:21
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 sethwebster/3802088127d24db84d8b4f7a40a5dac7 to your computer and use it in GitHub Desktop.
Save sethwebster/3802088127d24db84d8b4f7a40a5dac7 to your computer and use it in GitHub Desktop.
class ThereCanBeOnlyOne {
timeout = null;
performAction(waitMs, action) {
if (this.timeout) this.cancelPrevious();
return new Promise((resolve, reject) => {
this.timeout = setTimeout(() => {
this.cancelPrevious();
const value = action();
if (value.then && value.catch) {
this.handlePromise(value, resolve, reject);
} else {
resolve(value);
}
}, waitMs);
});
}
handlePromise(promise, resolve, reject) {
promise
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
}
cancelPrevious() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
}
export default ThereCanBeOnlyOne;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment