小程序倒计时
需求:根据创建时间来判断当前时间到截止日期还有多少天
/**
* 时间和期限关系处理函数
* @param {Number} range 限制截止的天数
* @param {string} creatTime 创建时间 2020-01-01 13:10:11
* @returns {void}
*/
timeFun(range = 7, creatTime) {
const that = this
creatTime = creatTime.replace(new RegExp('-','g'), '/')// ios兼容NAN问题 不支持2020-1-2 只支持2020/1/2
let nowtime = new Date().getTime()
let i = new Date(creatTime).getTime()
i+=range * 24 * 60 * 60*1000
let overtime = new Date(i).getTime()
let differenceDay = overtime-nowtime
// 大于截止日期返回
if(differenceDay < 0){
this.timerShow = false
return false;
}else{
this.timerShow = true
}
let day = Math.floor(differenceDay / 1000 / 60 / 60 / 24);//计算整数天数
let hour = Math.floor(differenceDay / 1000 / 60 / 60 % 24);//计算整数小时数
let min = Math.floor(differenceDay / 1000 / 60 % 60);//计算整数分
let afterMin = Math.floor(differenceDay / 1000 % 60);//取得算出分后剩余的秒数
console.log(differenceDay,day,hour,min,afterMin)
that.timeData.day = day
that.timeData.hour = hour
that.timeData.min = min
that.timeData.afterMin = afterMin
that.myInterval = setInterval(this.timing,1000)
},
// 递减逻辑
timing(){
const that = this
that.timeData.afterMin--
if(that.timeData.afterMin < 0){
--that.timeData.min
if(that.timeData.min < 0){
--that.timeData.hour
if(that.timeData.hour < 0){
--that.timeData.day
if(that.timeData.day == 0) {
that.timerShow = false
clearInterval(that.myInterval)
// 关闭之后的逻辑
// ....
}
that.timeData.hour = 0
// that.$set(that.timeData,'hour',0)
}
that.timeData.min = 59
// that.$set(that.timeData,'min',59)
}
that.timeData.afterMin = 59
// that.$set(that.timeData,'afterMin',59)
}
},
每次递减的时候计算时间感觉会影响性能 所以就把计算的时间的逻辑放到了外边,每次递减对应的数值就行而不是每次在做递减逻辑的时候计算时间
小程序隐藏的时候可以把这个定时器清除掉然后把都归为0,再显示的时候再调用方法计算