微信小程序 实现倒计时
效果如下:
1.wxml
<view class='l_lasttime'><label>距离限时特价仅剩</label>
<view class="container">
<text>{{clock}}</text>
<text>{{micro_second}}</text>
</view></view>
2.wxjs
//获取应用实例
const app = getApp()
const innerAudioContext = wx.createInnerAudioContext();
// 定义一个总毫秒数,以一天为例
var total_micro_second = 3600 * 1000 * 12;//这是一天倒计时
// var total_micro_second = 10 * 1000;//这是10秒倒计时
/* 毫秒级秒杀倒计时 */
function countdown(that) {
// 渲染倒计时时钟
that.setData({
clock: dateformat(total_micro_second)//格式化时间
});
if (total_micro_second <= 0) {
that.setData({
clock: "秒杀结束"
});
// timeout则跳出递归
return;
}
//settimeout实现倒计时效果
setTimeout(function () {
// 放在最后--
total_micro_second -= 10;
countdown(that);
}
, 10)//注意毫秒的步长受限于系统的时间频率,于是我们精确到0.01s即10ms
}
// 时间格式化输出,如1天天23时时12分分12秒秒12 。每10ms都会调用一次
function dateformat(micro_second) {
// 总秒数
var second = Math.floor(micro_second / 1000);
// 天数
var day = Math.floor(second / 3600 / 24);
// 总小时
var hr = Math.floor(second / 3600);
// 小时位
var hr2 = hr % 24;
// 分钟位
var min = Math.floor((second - hr * 3600) / 60);
// 秒位
var sec = (second - hr * 3600 - min * 60);// equal to => var sec = second % 60;
// 毫秒位,保留2位
var micro_sec = Math.floor((micro_second % 1000) / 10);
// return day + "天" + hr2 + "时" + min + "分" + sec + "秒" + micro_sec;
return hr2 + "时" + min + "分" + sec + "秒" ;
}
data: {
// 秒杀
clock: '',
},
onUnload: function () {
//卸载页面,清除计步器
clearInterval(this.data.durationIntval);
},
onLoad: function (options) {
countdown(this);
},