1.业务描述
通过微信支付开通vip,判断信息更新后再跳转

2.产生问题
通过setTimeout进行间隔一秒发送请求,数据比较,成功更新后通过wx.navigateTo跳转,此时setTimeout依然在后台持续调用

3.解决思路
setTimeout在每次调用后将生成一个标识符,而且每次都不同,所以用一个数组来保存起来,同时在页面离开时候清除所有的定时器

4.代码

data: {
  oldVal: '',
  timeList: []
},

onLoad: function(options) {
  this.pay()   
},

// 点击左上角返回箭头时候触发
onUnload: function(options) {
  for (let i = 0; i < this.data.timeList.length; i++) {
    clearTimeout(this.data.timeList[i])
  }
},

// 点击系统Home键返回上一步时候触发
onHide: function(options) {
  for (let i = 0; i < this.data.timeList.length; i++) {
    clearTimeout(this.data.timeList[i])
  }
},

checkIsUpdate: function () {
  wx.showLoading({
    title: '请稍候'
  })
  ajax((res)=>{
    let oldVal = this.data.oldVal
    let newVal = res.newVal
    let time = setTimeout(()=>{
      if (oldVal == newVal) {
        this.checkIsUpdate()
      } else {
        wx.hideLoading()
        wx.switchTab({
          url: '../my/my'
        })
      }
    }, 1000)
    this.data.timeList.push(time)
  })
},

pay: function () {
  let that = this
  payCallBack((res)=>{
    wx.showToast({
      title: '微信充值成功',
      icon: 'none',
      duration: 2000
      })
      that.checkIsUpdate()
  })
},

5.后记
在更新支付状态的时候可能发生用户离开当前页面,此时就需要清除计数器,否则,悬浮的模态框会在所有页面出现
用户离开页面包括两种动作,点击左上角的返回按钮,或者点击手机home键返回,这两种情况需要分别处理

6.其它方案

以上方案之所以要把所有延时句柄保存起来是因为,无法确定当前正在进入延时队列中的是具体的那个一,无法定点清除,所以就粗暴的将所有都保存起来,全部清除

后面经过思考,其实这里可以设置一个变量作为一个flag开关,在调用setTimeout时候先判断flag的值,在页面离开时候重置flag的值

作者 铁血 汉子 2019年9月4日
2024/04/26/02:52:29am 2019/9/4/8:48:04
0 7820