话不多说,直接上代码
js文件:
//timer.js
class Timecut {
constructor(concact) {
this.lock = false;
//是否展示天数
this.showDay = concact.showDay || false
this.argument = concact.argument
//获取传入的截止日期
this.send = concact.send //时间字符串
this.milliEndTime = concact.milliEndTime //时间戳
this.endCb = concact.endCb
if (!this.send && !this.milliEndTime) throw new Error("空的结束日期");
if (this.send && isNaN(this.send)) {
this.send = this.send.replace(/-/g, '/')
} else {
this.send = this.milliEndTime
}
if (concact.start && isNaN(concact.start)) {
this.now = new Date(concact.start.replace(/-/g, '/')).getTime()
} else if (concact.start) {
this.now = concact.start
} else {
this.now = new Date().getTime()
}
//获取函数外部的this
var that = this
//设置截止日期
this.endDate = new Date(this.send)
this.end = this.endDate.getTime();
//时间差
this.sendTime = (this.end - this.now) / 1000;
//执行倒计时方法
this.cut = setInterval(() => {
that.setTime();
this.sendTime--
}, 1000)
}
setTime() {
if (this.lock) { return false };
if (this.sendTime >= 0) {
this.d = this.formatTime(Math.floor(this.sendTime / 86400))
this.h = this.showDay ? this.formatTime(Math.floor((this.sendTime % 86400) / 3600)) : this.formatTime(Math.floor(this.sendTime / 86400) * 24 + Math.floor((this.sendTime % 86400) / 3600))
this.m = this.formatTime(Math.floor(((this.sendTime % 86400) % 3600) / 60))
this.s = this.formatTime(Math.floor(((this.sendTime % 86400) % 3600) % 60))
} else {
this.clearTimer();
this.endCb && this.endCb()
}
this.display([this.d||'00', this.h||'00', this.m||'00', this.s||'00'])
}
formatTime(val) {
return val < 10 ? `0${val}` : '' + val
}
clearTimer() {
clearInterval(this.cut)
this.cut = null;
this.lock = true;
}
display(time) {
let pages = getCurrentPages();
let prevPage = pages[pages.length - 1];
prevPage.setData({
[this.argument]: time
})
}
}
export default Timecut;
使用传入的参数argument,通过获取到当前页面栈的实例 getCurrentPages(),回传倒计时;
再来看wxml的创建单个倒计时实例
import countDownTimer from 'timer.js'
data: {
timeArr: null,
},
...
let set = {
milliEndTime: new Date().getTime() + time * 1000,
argument: 'timeArr',
endCb: this.endCb,
}
...
endCb(){}
...
this.countDownTimer = new countDownTimer(set);
...
//离开页面销毁倒计时
clearCountTimer() {
if (this.countDownTimer) {
this.countDownTimer.clearTimer();
this.countDownTimer = null;
}
}
创建倒计时数列
import Timecut from "timer.js";
...
data: {
cutdowns: [],
countDownTimer: [],
},
...
setCutDown(list) {
let cutdowns = this.data.countDownTimer
let initIndex = cutdowns.length
list.forEach((el, index) => {
let cuttime = `cutdowns[${initIndex + index}]`
let timer = new Timecut({
argument: cuttime,
start: el.systemTime,
send: el.expireDate,
endCb: (val) => this.endFunc(initIndex + index)
})
cutdowns.push({
countDownTimer: timer
})
})
this.setData({ countDownTimer: cutdowns })
},
...
// 清除倒计时
clearCountDownTimer() {
let countDownTimer = this.data.countDownTimer
countDownTimer.forEach(el => {
if (el.countDownTimer) {
el.countDownTimer.clearTimer()
el.countDownTimer = null
}
})
countDownTimer = []
this.setData({ countDownTimer })
},