UNPKG

live-model-bing

Version:

108 lines (91 loc) 2.59 kB
console.log("Hello world") const COUNT_IN_MILLIS = 10 const SECOND_IN_MILLIS = 100 * COUNT_IN_MILLIS const MINUTE_IN_MILLIS = 60 * SECOND_IN_MILLIS const HOUR_IN_MILLIS = 60 * MINUTE_IN_MILLIS const DAY_IN_MILLIS = 24 * HOUR_IN_MILLIS // 只有一位的数字前面补0 export function toFixed(num) { return `0${num}`.slice(-2) } class Countdown { constructor(ontick, endTimes, step = 200) { this.ontick = ontick this.endTimes = endTimes this.step = step this.status = Countdown.CountdownStatus.paused // 当前计数 this.remainTime = { days: 0, hours: 0, minutes: 0, seconds: 0, count: 0 } } /** * 开始计时 */ start() { this.status = Countdown.CountdownStatus.running this.ontick && this.ontick() this.countdown() } /** * 停止计时 */ pause() { this.status = Countdown.CountdownStatus.paused this.ontick && this.ontick() } /** * 停止计时 */ stop() { this.status = Countdown.CountdownStatus.stoped this.ontick && this.ontick() } /** * 计时数数逻辑 */ countdown() { if(this.status !== Countdown.CountdownStatus.running) { return } let count = this.endTimes - Date.now() count = count > 0 ? count : 0 this.remainTime = this.formatRemainTime(count) if(count > 0) { setTimeout(this.countdown.bind(this), this.step) }else{ this.stop() } // 重复调用可能导致多次diff this.ontick && this.ontick() } formatRemainTime(count) { const days = parseInt(count / DAY_IN_MILLIS) count = count % DAY_IN_MILLIS const hours = parseInt(count / HOUR_IN_MILLIS) count = count % HOUR_IN_MILLIS const minutes = parseInt(count / MINUTE_IN_MILLIS) count = count % MINUTE_IN_MILLIS const seconds = parseInt(count / SECOND_IN_MILLIS) count = count % SECOND_IN_MILLIS count = count / parseInt(COUNT_IN_MILLIS) count = count % COUNT_IN_MILLIS return { days, hours, minutes, seconds, count } } } Countdown.CountdownStatus = { running: "running", paused: "paused", stoped: "stoped" } export default Countdown