第一种方式:
(1)调用代码
var that = this;
this.sendCode()
(2)定时任务代码:
//定时任务(60秒后自动结束)
sendCode: function (e) {
var times = 0;
var i = setInterval(function () {
times++;
if (times >= 60) {
wx.showToast({//消息提示框
title: '结束定时任务',
icon: 'none',
duration: 2000
})
clearInterval(i);//关闭定时任务
} else {
//业务逻辑
}
}, 1000)
}
第二种方式:
(1)调用代码:直接使用。
(2)定时任务代码:
var that = this;
var times = 0;
that.setData({
selectCode: setInterval(function () {
times++;
if (times >= 60) {
clearInterval(that.data.selectCode);//关闭定时任务
} else {
//业务逻辑
}
}, 1000) //定时间隔时间 这里是1秒
})
第三种方式:
var timer; // 计时器
Page({
// ...省略
// 自定义的开始按钮
startBtn: function () {
console.log("开始按钮");
Countdown();
},
// 自定义的暂停按钮
pauseBtn: function () {
console.log("暂停按钮");
clearTimeout(timer);
},
});
// 倒计时
function Countdown() {
timer = setTimeout(function () {
console.log("----Countdown----");
Countdown();
}, 1000);
};