最近开发中遇到抢购倒计时和秒表的功能,都跟时间相关,功能也差不多。想到以后开发中会经常用到这种小功能,故记录分享一下。
小程序里的抢购倒计时:
onLoad: function (options) {
this.countdown("2020-6-4 18:46:13"); //传入限时的时间
},
countdown(time) {
const that = this;
var EndTime = new Date(time).getTime() ;
console.log("qianggou endtime" + EndTime);
var NowTime = new Date().getTime();
console.log("qianggou NowTime" + NowTime);
var total_micro_second = EndTime - NowTime;
if(total_micro_second < 0) {
this.data.qghour = 0;
this.data.qgminute = 0;
this.data.qgsecond = 0;
console.log("shouye qianggou finished:" + total_micro_second);
} else {
this.dateformat(total_micro_second);
console.log("shouye qianggou left time:" + total_micro_second);
}
this.setData({ //刷新页面timestr
qghour: this.data.qghour,
qgminute: this.data.qgminute,
qgsecond: this.data.qgsecond
});
setTimeout(function() { // 每1秒中刷新一次
total_micro_second -= 1000;
that.countdown(time);
}, 1000)
},
dateformat(micro_second) {
// 总秒数
var second = Math.floor(micro_second / 1000);
// 天数
this.data.qgday = Math.floor(second / 3600 / 24);
// 小时
this.data.qghour = Math.floor(second / 3600 % 24);
// 分钟
this.data.qgminute = Math.floor(second / 60 % 60);
// 秒
this.data.qgsecond = Math.floor(second % 60);
if (this.data.qgday < 10) {
this.data.qgday = '0' + this.data.qgday;
}
if (this.data.qghour < 10) {
this.data.qghour = '0' + this.data.qghour;
}
if (this.data.qgminute < 10) {
this.data.qgminute = '0' + this.data.qgminute;
}
if (this.data.qgsecond < 10) {
this.data.qgsecond = '0' + this.data.qgsecond;
}
},
快应用里实现的秒表:
startTimer() {
var d = new Date();
this.time = d.getTime();
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
this.timer = setInterval(this.showTime.bind(this), 1000);
},
stopTimer() {
this.currentTime = '00 : 00 : 00';
clearInterval(this.timer);
},
showTime() {
var d = new Date();
var ctime = d.getTime();
this.seconds = Math.trunc(((ctime - this.time)/1000)%60);
this.minutes = Math.trunc(((ctime - this.time)/1000)/60%60);
this.hours = Math.trunc(((ctime - this.time)/1000)/3600);
var timestr = '';
if(this.hours == 0) {
timestr += '00 : ';
} else {
timestr += this.hours +' : ';
}
if(this.minutes < 10) {
timestr += '0';
}
timestr += this.minutes;
timestr += ' : ';
if(this.seconds < 10) {
timestr += '0';
}
timestr += this.seconds;
this.currentTime = timestr;
console.log('showtime:' + this.currentTime);
},
onReady() {
this.startTimer();
},
总结一:
两段代码中分别用到了Math.tranc() 和Math.foor(),得到结果其实一样的,主要是由于这两段代码中传入的参数都是正数,所以这里取整的话两个都可以用。
总结二:
快应用和小程序差不多,尤其是js部分。但快应用里面的变量是实时刷新的,不用像小程序里一样需要不停调用setData 才能及时刷新。