小程序(倒计时的制作)
微信小程序如火如荼,今天我借教程做一篇倒计时效果的小程序页面.
这样的效果是怎样实现的呢
按以下步骤操作
wxml文件放个text:
<view>
<text>{{second}} 秒:{{micro_second}}</text>
</view>
然后在js文件下编写如下代码:
function countdown(that) {
var second = that.data.second
if (second == 0) {
// console.log("时间到...");
that.setData({
second: "Time Out..."
});
return;
} var time = setTimeout(function () {
that.setData({
second: second - 1
});
countdown(that);
}
, 1000)
}
在Page里面加入:
second: 3,
在onLoad加载函数里面执行倒计时函数:
countdown(this);
最终效果如图:
加入毫秒demo
更改js代码:
function countdown(that) {
var second = that.data.second
if (second == 0) {
that.setData({
second: "时间到!",
micro_second: " " ,
s:0
});
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);
}, 10)
}
在onload函数如加入上述的两个计时函数:
countdown(this);
countdown4micro(this);
最终效果: