定时器刷新问题?
发布于 7 年前 作者 tangjing 9732 次浏览 来自 官方Issues
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;

求大佬指导;

5 回复

在time函数里先执行清除定时器

time: function () {
    var that = this;
    if (that.data.timer) {
        clearTimeout(that.data.timer)

    }

   ...........

    // 创建并保存定时器name     
  },

上代码吧

上代码吧

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)

    })()

}

回到顶部