Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
Add Comment
Please, Sign In to add comment