微信小程序 撸一个活动倒计时
在公司中做一款微信小程序,其中有个活动模块用到了 倒计时,把自己写的方法共享出来,供新手学习,也希望能大神有更好的方法提供,欢迎指正
首先获取活动状态
活动状态用来在页面展示给用户当前活动的进度,同时是我们倒计时判断的依据;
// 获取活动状态(开始、进行中、结束)
getActiveStat: function (cb) {
let now = this.getNowTime(),
start = this.data.startTime, //活动开始时间,后台传过来;
end = this.data.endTime; //活动结束时间,后台传过来;
let stat = now < start ? 0 : (now < end ? 1 : 2); //这里我用0、1、2 分别表示活动开始、进行中、结束;
if (typeof cb === 'function') cb(stat) //这里是一个回调方法,获取活动状态后回调里写倒计时
},
// 获取当前时间(由于客户端时间可能不准确,当前时间最好由后端来获取)
getNowTime: function () {
let now = new Date();
return now.getTime() / 1000;
},
倒计时方法
//倒计时
countDown: function (now, contrast) {
let t = setInterval( () => {
now += 1 ;
let diff = contrast - now; //时间差,用来计算时间;
if(diff > 0) {
this.computeTime(diff);
} else {
clearInterval(t);
this._callback(this.data.timeTitle)
}
}, 1000)
},
//计算时间
computeTime: function (t) {
let day = Math.floor(t / (60 * 60 * 24));
let hour = Math.floor((t / (60 * 60)) % 24);
let min = Math.floor((t / 60) % 60);
let sec = Math.floor(t % 60);
hour = hour < 10 ? "0" + hour : hour;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
this.setData({ //最终要显示在页面的数据;
time: {
day: day,
hour: hour,
min: min,
sec: sec,
}
})
},
// 写一个初始化函数,调动倒计时方法
init: function (stat) {
this.setData({ activeStat: stat }) //设置活动状态
if (stat === 2) return this._callback(2);
let now = this.getNowTime();
let contrast = stat === 0 ? this.data.startTime : this.data.endTime; //通过活动状态,来判断我们要与那个时间做对比,用来做倒计时;
this.countDown(now, contrast);
},
在页面加载时调用
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getTimeTitle((res) => {
this.init(res);
})
},
回调方法
这里倒计时结束后处理一些事情,比如,重新获取数据来刷新页面等;如果写在组件,可以在回调里向父级页面发送数据
// 回调方法
_callback: function(stat) {
if(stat && stat === 2) {
return console.log('callback',2);
}
stat ++; //活动状态+1;
this.init(stat); // 结束后重新调用倒计时来更新活动状态和时间
console.log('callback');
}