倒计时适用于很多场景,先mark下来,以备之后的一时之用吧
以下案例是24小时的倒计时
wxml:
<view>倒计时 {{countHour}}:{{countMinute}}:{{countSecond}}</view>
js:
data: {
countDay: null,
countHour: null,
countMinute: null,
countSecond: null,
},
onReady: function () {
this.setData({
countDay: '00',
countHour: '24',
countMinute: '00',
countSecond: '00',
});
// 设置开始时间,1天=86400秒
var totalSecond = 86400 - 1;
// 设置定时器
var timeInterval = setInterval(function () {
// 天
var day = Math.floor(totalSecond / 3600 / 24);
if (day < 10) day = '0' + day;
// 时
var hour = Math.floor((totalSecond - day * 3600 * 24) / 3600);
if (hour < 10) hour = '0' + hour;
// 分
var minute = Math.floor((totalSecond - day * 3600 *24 - hour * 3600) / 60);
if (minute < 10) minute = '0' + minute;
// 秒
var second = totalSecond - day * 3600 * 24 - hour * 3600 - minute*60;
if (second < 10) second = '0' + second;
this.setData({
countDay: day,
countHour: hour,
countMinute: minute,
countSecond: second,
});
totalSecond--;
if (totalSecond < 0) {
clearInterval(timeInterval);
wx.showToast({
title: '倒计时结束',
});
this.setData({
countDay: '00',
countHour: '00',
countMinute: '00',
countSecond: '00',
});
}
}.bind(this), 1000);
},