1. 程式人生 > 其它 >微信小程式定時執行及清除定時器

微信小程式定時執行及清除定時器

十年河東,十年河西,莫欺少年窮

學無止境,精益求精

程式碼如下:

// pages/setIntervals/setIntervals.js
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    Numbers: 0,
    NumbersTimeOut: 0,
    Interval: null,
    timeOut: null
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    this.getdata2();
  },

  ///重複執行
  getdata() {
    let that 
= this; that.data.Interval = setInterval(() => { that.setData({ Numbers: ++that.data.Numbers }) console.log(that.data.Numbers) }, 1000); }, ///執行一次 方法體內用了遞迴,清除的時候,有可能又被重新賦值--不建議使用遞迴呼叫 有可能清除不掉 getdata2() { let that = this; that.data.timeOut = setTimeout(() => { that.setData({ NumbersTimeOut:
++that.data.NumbersTimeOut }) console.log(that.data.NumbersTimeOut) this.getdata2(); }, 1000); }, /** * 生命週期函式--監聽頁面隱藏 */ onHide: function () { let that = this clearInterval(that.data.Interval); clearTimeout(that.data.timeOut); }, /** * 生命週期函式--監聽頁面解除安裝
*/ onUnload: function () { let that = this clearInterval(that.data.Interval); clearTimeout(that.data.timeOut); }, })

詳情參考:https://developers.weixin.qq.com/miniprogram/dev/reference/api/setTimeout.html

@天才臥龍的部落格

付婷,你還那麼胖嗎?如果胖,就減肥肥吧。