微信小程序定时执行及清除定时器 及 this.setData({}) 设置对象内属性

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

代码如下:

// 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

设置对象内属性:

  data: {
    Numbers: 0,
    NumbersTimeOut: 0,
    Interval: null,
    timeOut: null,
    txt:{
      v1:'1',
      v2:'2'
    }
  },

  bindinput(e) {
    let {v1,v2}=this.data.txt;
    this.setData({
      'txt.v1':e.detail.value
    })
  },

@天才卧龙的博客

原文地址:https://www.cnblogs.com/chenwolong/p/15597402.html