显示当前时间 ( setInterval() 函数会每秒执行一次函数,类似手表)。使用clearInterval() 来停止执行:
- clearInterval() 方法可取消由 setInterval() 函数设定的定时执行操作。
- clearInterval() 方法的参数必须是由 setInterval() 返回的 ID 值。
- 注意: 要使用 clearInterval() 方法, 在创建执行定时操作时要使用全局变量:
以下是在微信小程序的一个interval.js
页面展示的setInterval()
和clearInterval()
方法的demo:
./interval.js
let interval = null;
Page({
data: {
countDown: 60,
timeMsg: '重新开始',
},
onLoad: function () {
this.setCountdown();
}
onHide: function () {
clearInterval(interval);
},
onUnload: function () {
clearInterval(interval);
},
setCountdown: function () {
var _this = this;
var countDown = _this.data.countDown;
interval = setInterval(function () {
countDown--;
_this.setData({
timeMsg: '剩下 ' + countDown + ' 秒'
})
if (countDown <= 0) {
clearInterval(interval);
_this.setData({
timeMsg: '重新开始',
countDown: 60
})
}
}, 1000)
},
})