注意iso不能识别2019-1-2这样的时间,正则替换成2019/1/2
var endDate = new Date(2019-1-2 12:30:56);//设置截止时间返回的事NAN
if(isNaN(endDate)){
// iso不能识别2018-08-30格式时间
var timer1=timer.replace(/-/g, '/');
var endDate=new Date(timer1)
}
1.单一定时器
methods:{
countTime(timer) {
var that = this;
if(!timer){
return
}
this.countTimer= setInterval(()=>{
var date = new Date();
var now = date.getTime();
var endDate = new Date(timer);//设置截止时间
if(isNaN(endDate)){
// iso不能识别2018-08-30格式时间
var timer1=timer.replace(/-/g, '/');
var endDate=new Date(timer1)
}
var end = endDate.getTime();
var leftTime = end - now; //时间差
var d, h, m, s, ms;
if (leftTime >= 0) {
d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
m = Math.floor(leftTime / 1000 / 60 % 60);
s = Math.floor(leftTime / 1000 % 60);
// ms = Math.floor(leftTime % 1000);
// ms = ms < 100 ? "0" + ms : ms
s = s < 10 ? "0" + s : s
m = m < 10 ? "0" + m : m
h = h < 10 ? "0" + h : h
// this.countdown=d + ":" + h + ":" + m + ":" + s + ":" + ms;
// console.log(this.countdown)
this.day=d;
this.hour=h;
this.min=m;
this.second=s
} else {
this.countFlag=false
}
},1000)
},
}
2.一个页面内多个倒计时与清除
多个定时器,离开当前路由清除:思路把生成的定时器放在数组中,离开时遍历清除
小知识点:数组对象[{a:1,b:2}],新增c的值为3,因为有多个定时器再进行着this.$forceupdate()会造成屏幕闪烁,因为全部数据刷新了一遍。
用到了this.$set(this.a,index,{...this.a[index],{c:3}}即可利用了es6的扩展运算符
countTime(item,index) {
var that = this;
const timer=setInterval(()=>{
var date = new Date();
var now = date.getTime();
var endDate = new Date(item.timer);//设置截止时间
if(isNaN(endDate)){
// iso不能识别2018-08-30格式时间
var timer1=item.timer.replace(/-/g, '/');
var endDate=new Date(timer1)
}
var end = endDate.getTime();
var leftTime = end - now; //时间差
var d, h, m, s, ms;
// if(leftTime>=86400){//小于1小时才显示倒计时
// that.$set(this.discountTimer,index,{...this.discountTimer[index],showLimitData:true})
// }
if (leftTime >= 0) {
d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
m = Math.floor(leftTime / 1000 / 60 % 60);
s = Math.floor(leftTime / 1000 % 60);
// ms = Math.floor(leftTime % 1000);
// ms = ms < 100 ? "0" + ms : ms
s = s < 10 ? "0" + s : s
m = m < 10 ? "0" + m : m
h = h < 10 ? "0" + h : h
// this.countdown=d + ":" + h + ":" + m + ":" + s + ":" + ms;
// console.log(d + ":" + h + ":" + m + ":" + s + ":" + ms)
if(leftTime>=86400){//小于1小时才显示倒计时
that.$set(this.discountTimer,index,{...this.discountTimer[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'showLimit'})
}else{
that.$set(this.discountTimer,index,{...this.discountTimer[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'hideLimit'})
}
} else {
that.$set(this.discountTimer,index,{...this.discountTimer[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'timeOut'})//显示活动结束
console.log('已截止')
}
},1000)
this.countTimer.push(timer)
},
clearAllInterval(){//清除所有定时器
this.countTimer.forEach(item=>{
if(item){
clearInterval(item)
}
})
}