版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1.引入插件timer.js
var Timer= require(’…/…/utils/timer.js’);
2.在 onLoad 周期初始化,第二个参数17为需要计时的总秒数
onLoad: function () {
this.timer= new Timer(this,17);
}
3. 在任意的方法中,调用start方法触发倒计时
this.timer.start();
4. timer.js 代码如下
// 倒计时
class Timer{
constructor(page, second) {
this.page = page;
this.page.setData({ time: second});
this.initSeconds = second;
}
start() {
console.log('进入倒计时');
var that = this;
var seconds = that.initSeconds;
that.page.setData({ time: seconds});
let promise = new Promise((resolve, reject) => {
let setTimer = setInterval(
() => {
seconds -= 1;
that.page.setData({
time: seconds,
})
if (seconds <= 0) {
that.page.setData({
time: '0'
})
resolve(setTimer)
}
}
, 1000)
})
promise.then((setTimer) => {
console.log('清除计时器');
clearInterval(setTimer)
})
}
}
module.exports = Timer;