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); } }