微信小程序手机验证码获取倒计时 刷新页面也会继续

wx.ml

  <view class="item {{change2?'change_border':''}}">
        <label for="">验证码</label>
        <input type="testmsg"  value="{{testmsg}}" data-index="2" bindblur="nochanegBorder" bindinput="changeValue" bindfocus="changeBorder" placeholder="请输入密码" />
        <view class="test {{getTest?'':'test_active'}}" bindtap="{{getTest?'':'getTestMsg'">{{getTest?'重新获取'+waitTime/1000+'S':'获取验证码'}}</view>
    </view>

wx.js

  onLoad: function (options) {
    let that = this;
    let waitTime = wx.getStorageSync('waitTime')
    let getTest = wx.getStorageSync('getTest')
    if (waitTime) {
      that.setData({
        waitTime
      },()=>{
        if(waitTime!==0 && waitTime!==60000){
          that.getTestMsg()
        }
      })
    } else {
      wx.setStorageSync('waitTime', 60000)
    }
    if (getTest) {
      that.setData({
        getTest
      })
    } else {
      wx.setStorageSync('getTest', false)
    }
  },

  getTestMsg() {
    const that = this;
    let waitTime = wx.getStorageSync('waitTime');
    console.log(waitTime)
    if (!that.data.getTest) {
      that.setData({
        getTest: true
      },()=>{
        wx.setStorageSync('getTest',true)
      })
    }
    //发送验证码
    if (waitTime == 0) {
      that.setData({
        getTest: false
      }, () => {
        wx.setStorageSync('waitTime', 60000)
        wx.setStorageSync('getTest', false)
      })
      //重新获取验证码
    } else {
      setTimeout(() => {
        waitTime = waitTime - 1000;
        that.setData({
          waitTime
        }, () => {
          wx.setStorageSync('waitTime', waitTime)
          return that.getTestMsg()
        })
      }, 1000)
    }
  }

 

微信小程序验证码JS获取最新

 demo() {
    const that=this;
    //获取最新时间
    let newTime = new Date().getTime();
    //获取旧时间
    wx.getStorage({
      key: "oldTime",
      complete(res) {
        //旧时间不存在
        if (!res.data) {
          wx.setStorage({
            key: "oldTime",
            data: newTime,
            success() {
                //递归调用demo
                return that.demo();
            }
          })
        } else {
          //旧时间存在
          let oldTime = res.data;
          let Timeresult = parseInt((newTime - oldTime) / 1000) * 1000;
          if (Timeresult >60000) {
            //清楚旧时间
            wx.removeStorage({
              key: 'oldTime'
            })
          } else {
            //延时
            setTimeout(() => {
              that.setData({
                waitTime:(60000 - Timeresult)/1000
              },()=>{
                if(Timeresult==0){
                  //发送验证码
                  return that.demo();
                }else{
                  //递归调用demo
                  return that.demo();
                }
              })
            }, 1000)
          }
        }
      }
    })
  }

 

posted @ 2021-08-30 16:16  还有什么值得拥有  阅读(195)  评论(0编辑  收藏  举报