小程序實現計時器功能
本文實例為大傢分享瞭小程序實現計時器功能的具體代碼,供大傢參考,具體內容如下
效果圖如下
佈局(.wxml)
<view class="countTime">{{timecount}}</view> <button class="aaa" bindtap="start">開始</button> <button class="aaa" bindtap="stop">暫停</button> <button class="aaa" bindtap="Reset">停止</button>
樣式(.css)
/* 小程序計時器 */ .countTime{ height:200px; font-size:30px; line-height:200px; text-align: center; } .aaa{ width:150px; background:rgb(7, 193, 96); color:#fff; margin-bottom:8px; }
效果(.js)
var init; Page({ data: { //小程序計時器 hour:0, minute:0, second:0, millisecond:0, timecount:'00:00:00', cost:0, flag:1, endtime:"", }, start:function(){ clearInterval(init); var that=this; that.setData({ hour:0, minute:0, second:0, millisecond:0 }) init=setInterval(function(){ that.timer() },50); }, stop:function(){ clearInterval(init); }, Reset:function(){ var that=this; clearInterval(init); 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 }) } });
註意的點: 在點擊啟動定時器按鈕時,多次連著點擊,會累加定時器,會造成定時器加速的效果,為瞭避免這種情況,應該在每次點擊開始前先清除一下定時器。
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。