Created
November 15, 2018 14:21
-
-
Save sethwebster/3802088127d24db84d8b4f7a40a5dac7 to your computer and use it in GitHub Desktop.
This file contains 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
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