微信小程序中,JS中setInterval()和clearInterval()的使用以及注意事项

显示当前时间 ( setInterval() 函数会每秒执行一次函数,类似手表)。使用clearInterval() 来停止执行:
  1. clearInterval() 方法可取消由 setInterval() 函数设定的定时执行操作。
  2. 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 () {
    //因为interval函数中的this域不一样了,需要把页面的this提取出来
    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)
  },

})


猜你喜欢

转载自blog.csdn.net/aspire_cj/article/details/107400653