之前写了一个小程序倒计时的demo,在网上查看了一下,计时器很少有demo,现在来写一个。
wxml
<view class="container"> {{timecount}}</view> <button bindtap='start'>开始</button> <button bindtap='stop'>暂停</button> <button bindtap='Reset'>停止</button>
JS
var intt; Page({ data: { hour: 0, minute: 0, second: 0, millisecond: 0, timecount: '00:00:00', cost: 0, flag: 1, endtime: "", }, onLoad: function () { }, //开始 start: function () { var that = this; //停止(暂停) clearInterval(intt); //时间重置 that.setData({ hour: 0, minute: 0, second: 0, millisecond: 0, }) intt = setInterval(function () { that.timer() }, 50); }, //暂停 stop: function () { clearInterval(intt); }, //停止 Reset: function () { var that = this clearInterval(intt); that.setData({ hour: 0, minute: 0, second: 0, millisecond: 0, timecount: '00:00:00', }) }, timer: function () { var that = this; console.log(that.data.millisecond) that.setData({ millisecond: that.data.millisecond + 5 }) if (that.data.millisecond >= 100) { that.setData({ millisecond: 0, second: that.data.second + 1 }) } if (that.data.second >= 60) { that.setData({ second: 0, minute: that.data.minute + 1 }) } if (that.data.minute >= 60) { that.setData({ minute: 0, hour: that.data.hour + 1 }) } that.setData({ timecount: that.data.hour + ":" + that.data.minute + ":" + that.data.second + ":" + that.data.millisecond }) }, });
css:
.container{ height:200rpx; line-height:200rpx; font-size:50rpx; } button{ width:150rpx; background: rgb(7, 193, 96); color: #fff; margin-bottom: 8px; }
要是样式css不想写了,可以用组件库,
如果组件库不会使用,可以查看教程