小程序简单计时器的制作,也可用于倒计时,以录音计时为例:
- // 计时器
- function timer(that){
- // timeout则跳出递归
- if (that.data.record == 0){
- return;
- }
- if(that.data.min == 10){
- return;
- }
- let sec = that.data.sec * 1
- let min = that.data.min * 1
- sec += 1
- if(sec < 10){
- sec = '0' + sec;
- }else if(sec == 60){
- sec = '00'
- min += 1
- }
- if(min < 10){
- min = '0' + min
- }
- that.setData({
- sec: sec,
- min: min
- })
- setTimeout(function(){
- timer(that);
- },1000)
- }
- Page({
- /**
- * 页面的初始数据
- */
- data: {
- record: 0, // 录音按钮显示状态
- sec: '00',
- min: '00',
- },
- // 开始录音
- startRecord: function (e) {
- let that = this;
- that.setData({
- sec: '00'
- })
- recorderManager.start(options);
- recorderManager.onStart(() => {
- that.setData({
- record: 1
- })
- timer(that);
- })
- },
- // 停止录音
- stopRecord: function (e) {
- let that = this;
- recorderManager.stop();
- recorderManager.onStop((res) => {
- console.log('recorder stop', res)
- const { tempFilePath } = res
- wx.showToast({
- title: '录音保存成功',
- icon: 'success',
- duration: 2000
- })
- that.setData({
- record: 0
- })
- timer(that);
- })
- },
- })
感谢博主, 正好用到。