js封装倒计时,两种类型;
程序员文章站
2022-04-14 16:43:16
...
由于本者最近在写一个 小程序拼团抽奖的活动;所以就总结封装了两种需要用到的倒计时;
//文件: utils/utils.js
//小于10的格式化函数
export function timeFormat(param){
return param < 10 ? '0' + param : param;
}
//注意引入:
import {timeFormat} from "@/utils/utils.js"
1: 例子: 参加拼团成功后:拼团剩余时间的倒计时
封装JS:
//注意引入:
import {timeFormat} from "@/utils/utils.js"
// 针对某时间~现在的倒计时()
// parms: (1)时长=>小时duration(2)拼团成功的时间戳 timestamp
// return 剩余时长(residueObj:{day:'10',hour:'01',min:"12",sec:'59'})
export function countDown(timestamp,duration){
let residueObj ={};
let newTime = new Date().getTime();
let time1 = new Date(timestamp).getTime();
let durationTimestamp = Number(duration)*60*60*1000
let endTime = parseInt(time1)+parseInt(durationTimestamp);//+时长的时间戳
if (endTime - newTime > 0){
let time = (endTime - newTime) / 1000;
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
residueObj.day = timeFormat(day),
residueObj.hour= timeFormat(hou),
residueObj.min = timeFormat(min),
residueObj.sec = timeFormat(sec)
}else{//活动已结束,全部设置为'00'
residueObj.day ="00"
residueObj.hour ="00"
residueObj.min ="00"
residueObj.sec ="00"
}
return residueObj
}
使用:
import {countDown} from "../../utils/index.js"
this.countDownTimer = setInterval(()=>{
this.countDownData =countDown('2019-07-19 13:17:12','5');
},1000);
打印结果:
2: 距开奖的倒计时
封装JS:
//注意引入:
import {timeFormat} from "@/utils/utils.js"
// 倒计时List(例子:商品抽奖开始倒计时)
// parms actEndTimeList=>倒计时日期列表( ['2019-07-28 12:12:12','2019-07-20 10:00:'])
// retrun (countDownArr) json (day,hou,min,sec)
export function countDownList(actEndTimeList){
let _this = this;
// 获取当前时间,同时得到活动结束时间数组
let newTime = new Date().getTime();
let endTimeList =actEndTimeList;
let countDownArr = [];
endTimeList.forEach(item => {
let endTime = new Date(item).getTime();
let obj = null;
if (endTime - newTime > 0){
let time = (endTime - newTime) / 1000;
// 获取天、时、分、秒
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
obj = {
day: timeFormat(day),
hou: timeFormat(hou),
min: timeFormat(min),
sec: timeFormat(sec)
}
}else{//活动已结束,全部设置为'00'
obj = {
day: '00',
hou: '00',
min: '00',
sec: '00'
}
}
countDownArr.push(obj);
})
return countDownArr
}
使用:
import {listDataTimer } from "../../utils/index.js"
let listTime = ['2019-07-28 12:12:12','2019-07-20 10:00:00']
this.listDataTimer =setInterval(()=>{
this.listData = countDownList(listTime);
},1000)
打印结果:
如果能帮到你我很开心。
不管好的坏的欢迎留言,谢谢!