wxml文件放个text
second: {{second}} micro second:{{micro_second}}
在js文件中调用
function countdown(that) {
var second = that.data.second
if (second == 0) {
// console.log("Time Out...");
that.setData({
second: "Time Out..."
});
return ;
}
var time = setTimeout(function(){
that.setData({
second: second - 1
});
countdown(that);
}
,1000)
}
Page({
data: {
second: 3
},
onLoad: function() {
countdown(this);
}
});
运行验证下,从10走到1s,然后显示时间到。
于是继续将毫秒完善,注意毫秒的步长受限于系统的时间频率,于是我们精确到0.01s即10ms
js
/* 秒级倒计时 */
function countdown(that) {
var second = that.data.second
if (second == 0) {
that.setData({
second: "Time out!",
micro_second: "micro_second too."
});
clearTimeout(micro_timer);
return ;
}
var timer = setTimeout(function(){
that.setData({
second: second - 1
});
countdown(that);
}
,1000)
}
/* 毫秒级倒计时 */
// 初始毫秒数,同时用作归零
var micro_second_init = 100;
// 当前毫秒数
var micro_second_current = micro_second_init;
// 毫秒计时器
var micro_timer;
function countdown4micro(that) {
if (micro_second_current <= 0) {
micro_second_current = micro_second_init;
}
micro_timer = setTimeout(function(){
that.setData({
micro_second: micro_second_current - 1
});
micro_second_current--;
countdown4micro(that);