1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- export class Countdown {
- constructor(expiredDate, onRender, onComplete) {
- this.onRender = onRender;
- this.onComplete = onComplete;
- this.setExpiredDate(expiredDate);
- }
- setExpiredDate(expiredDate) {
- // get the current time
- const currentTime = new Date().getTime();
- // calculate the remaining time
- this.timeRemaining = expiredDate.getTime() - currentTime;
- this.timeRemaining <= 0 ?
- this.complete() :
- this.start();
- }
- complete() {
- if (typeof this.onComplete === 'function') {
- this.onComplete();
- }
- }
- static getTime(time) {
- return {
- days: Math.floor(time / 1000 / 60 / 60 / 24),
- hours: Math.floor(time / 1000 / 60 / 60) % 24,
- minutes: Math.floor(time / 1000 / 60) % 60,
- seconds: Math.floor(time / 1000) % 60
- };
- }
- update() {
- if (typeof this.onRender === 'function') {
- this.onRender(Countdown.getTime(this.timeRemaining));
- }
- }
- start() {
- // update the countdown
- this.update();
- // setup a timer
- const intervalId = setInterval(() => {
- // update the timer
- this.timeRemaining -= 1000;
- if (this.timeRemaining < 0) {
- // call the callback
- this.complete();
- // clear the interval if expired
- clearInterval(intervalId);
- } else {
- this.update();
- }
- }, 1000);
- }
- }
|