微信小程序 简单计时器制作

小程序简单计时器的制作,也可用于倒计时,以录音计时为例:

1. // 计时器
2. function timer(that){
3.   // timeout则跳出递归
4.   if (that.data.record == 0){
5.     return;
6.   }
7.   if(that.data.min == 10){
8.     return;
9.   }
10.   let sec = that.data.sec * 1
11.   let min = that.data.min * 1
12.   sec += 1
13.   if(sec < 10){
14.     sec = '0' + sec;
15.   }else if(sec == 60){
16.     sec = '00'
17.     min += 1
18.   }
19.   if(min < 10){
20.     min = '0' + min
21.   }
22.   that.setData({
23.     sec: sec,
24.     min: min
25.   })
26.   setTimeout(function(){
27.     timer(that);
28.   },1000)
29. }
30. Page({
31.
32.   /**
33.    * 页面的初始数据
34.    */
35.   data: {
36.     record: 0, // 录音按钮显示状态
37.     sec: '00',
38.     min: '00',
39.   },
40.
41.   // 开始录音
42.   startRecord: function (e) {
43.     let that = this;
44.     that.setData({
45.       sec: '00'
46.     })
47.     recorderManager.start(options);
48.     recorderManager.onStart(() => {
49.       that.setData({
50.         record: 1
51.       })
52.       timer(that);
53.     })
54.   },
55.   // 停止录音
56.   stopRecord: function (e) {
57.     let that = this;
58.     recorderManager.stop();
59.     recorderManager.onStop((res) => {
60.       console.log('recorder stop', res)
61.       const { tempFilePath } = res
62.       wx.showToast({
63.         title: '录音保存成功',
64.         icon: 'success',
65.         duration: 2000
66.       })
67.       that.setData({
68.         record: 0
69.       })
70.       timer(that);
71.     })
72.   },
73. })