counter.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. export class Countdown {
  2. constructor(expiredDate, onRender, onComplete) {
  3. this.onRender = onRender;
  4. this.onComplete = onComplete;
  5. this.setExpiredDate(expiredDate);
  6. }
  7. setExpiredDate(expiredDate) {
  8. // get the current time
  9. const currentTime = new Date().getTime();
  10. // calculate the remaining time
  11. this.timeRemaining = expiredDate.getTime() - currentTime;
  12. this.timeRemaining <= 0 ?
  13. this.complete() :
  14. this.start();
  15. }
  16. complete() {
  17. if (typeof this.onComplete === 'function') {
  18. this.onComplete();
  19. }
  20. }
  21. static getTime(time) {
  22. return {
  23. days: Math.floor(time / 1000 / 60 / 60 / 24),
  24. hours: Math.floor(time / 1000 / 60 / 60) % 24,
  25. minutes: Math.floor(time / 1000 / 60) % 60,
  26. seconds: Math.floor(time / 1000) % 60
  27. };
  28. }
  29. update() {
  30. if (typeof this.onRender === 'function') {
  31. this.onRender(Countdown.getTime(this.timeRemaining));
  32. }
  33. }
  34. start() {
  35. // update the countdown
  36. this.update();
  37. // setup a timer
  38. const intervalId = setInterval(() => {
  39. // update the timer
  40. this.timeRemaining -= 1000;
  41. if (this.timeRemaining < 0) {
  42. // call the callback
  43. this.complete();
  44. // clear the interval if expired
  45. clearInterval(intervalId);
  46. } else {
  47. this.update();
  48. }
  49. }, 1000);
  50. }
  51. }