vue 一个页面多个定时器
有时候我们一个页面会有多个倒计时,但是总不能有几个倒计时就写几个倒计时的方法吧???下面就是多个倒计时的方法timer:[],// 定时器开关counts:[{countNumber:0,},{countNumber:0,},],methods:{init(){//
·
有时候我们一个页面会有多个倒计时,但是总不能有几个倒计时就写几个倒计时的方法吧???下面就是多个倒计时的方法
timer:[], // 定时器开关
counts:[
{
countNumber:0,
},
{
countNumber:0,
},
],
methods:{
init(){
//获取当前时间
let cur = new Date().getTime();
//设置截止时间
let str=[
"2022/6/30 00:00:00",
"2022/7/1 00:00:00",
];
// 倒计时
this.counts.map((item,index)=>{
// 当前时间减去停止时间
let leftTime = parseInt((new Date(str[index])-cur)/1000)
this.count(leftTime,(msg)=>{
item.countNumber=msg;
})
})
},
// 倒计时
count(time,fn){
let t=this;
let times=time;
ti()
this.timer.push(setInterval(ti,1000))
function ti(){
times--
// 定义变量 h,m,s保存倒计时的时间
let h,m,s;
if (times>=0) {
// 时分秒
h = Math.floor(times/60/60);
m = Math.floor(times/60%60);
s = Math.floor(times%60);
let msg=t.repair(h)+':'+t.repair(m)+':'+t.repair(s);
fn(msg);
}else{
// 关闭定时器
clearInterval(t.timer);
return false
}
}
},
// 数字补0
repair(o){
let x=o;
let t=x > 9 ? x : '0' + x
return t
},
// 关闭定时器
stopInter(){
this.timer.map((item)=>{
clearInterval(item);
})
},
}
更多推荐
已为社区贡献2条内容
所有评论(0)