time: function () { var that = this ; // 创建并保存定时器name that.data.timer = setTimeout( function () { if (second <= 0){ //清除计时器 clearTimeout(that.data.timer); } //second是设置的倒计时值,secondshow是要展示的key that.setData({ secondshow: second-- }) if (second == 0){ that.jisuan(); } else { if (second > 0){ that.time(); } } }, 1000) }, |
我在小程序中设置了一个定时器,每秒刷新一次,对一个值进行自减;
在电脑上上显示没问题,每秒减一,但是在手机上预览时每次减2;
求大佬指导;
time(){
var that = this
let second = 10, handle = 0, loop
(loop = () => {
handle = setTimeout(function () {
if (handle) {
//清除计时器
clearTimeout(handle)
handle = 0
}
that.setData({
secondshow: second--
})
if (second <= 0) {
clearTimeout(handle)
handle = 0
that.jisuan()
} else {
loop()
}
}, 1000)
})()
}
在time函数里先执行清除定时器
time:
function
() {
var
that =
this
;
if
(that.data.timer) {
clearTimeout(that.data.timer)
}
...........
// 创建并保存定时器name
},
https://developers.weixin.qq.com/s/8801NymG7Jcr 试下
上代码吧
上代码吧
time: function () {
var that = this;
// 创建并保存定时器name
that.data.timer = setTimeout(function () {
if(second <= 0){
//清除计时器
clearTimeout(that.data.timer);
}
//second是设置要倒计时的值,secondshow是要展示的
that.setData({
secondshow: second--
})
if(second == 0){
that.jisuan();
}else{
if(second > 0){
that.time();
}
}
}, 1000)
},
onLoad() {
if (this.data.timer) {
clearTimeout(this.data.timer)
}
this.loadTime()
},
loadTime: function() {
this.data.timer = setTimeout(() => {
let second = this.data.second - 1
if (second <= 0) {
if (this.data.timer) {
clearTimeout(this.data.timer)
}
this.jisuan()
} else {
this.setData({
second: second
})
this.loadTime()
}
}, 1000)
},
onUnload() {
if (this.data.timer) {
clearTimeout(this.data.timer)
}
},