Guest User

Untitled

a guest
Nov 15th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. class ThereCanBeOnlyOne {
  2. timeout = null;
  3.  
  4. performAction(waitMs, action) {
  5. if (this.timeout) this.cancelPrevious();
  6. return new Promise((resolve, reject) => {
  7. this.timeout = setTimeout(() => {
  8. this.cancelPrevious();
  9. const value = action();
  10. if (value.then && value.catch) {
  11. this.handlePromise(value, resolve, reject);
  12. } else {
  13. resolve(value);
  14. }
  15. }, waitMs);
  16. });
  17. }
  18.  
  19. handlePromise(promise, resolve, reject) {
  20. promise
  21. .then((res) => {
  22. resolve(res);
  23. })
  24. .catch((err) => {
  25. reject(err);
  26. });
  27. }
  28.  
  29. cancelPrevious() {
  30. if (this.timeout) {
  31. clearTimeout(this.timeout);
  32. this.timeout = null;
  33. }
  34. }
  35. }
  36.  
  37. export default ThereCanBeOnlyOne;
Add Comment
Please, Sign In to add comment