微信小程序 實現倒計時
效果如下:
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);
},