其他分享
首页 > 其他分享> > Vue设置定时器和清除定时器—微信支付轮询

Vue设置定时器和清除定时器—微信支付轮询

作者:互联网

业务需求:
打开微信支付模态框,扫码,二维码有效期为5分钟,5分钟后关闭模态框,支付成功后关闭模态框并跳转页面。
在这里插入图片描述
需求分析:
在项目中遇到支付完成后轮询,获取当前的最新支付状态,确定订单是否支付成功。此时需要设置定时器。
如果定时器不及时地清除,会造成浏览器崩掉,请求多次可能会使服务器崩掉,此时就需要清除定时器。
在某个页面中启动定时器后,一定要在页面关闭时将定时器清除掉,在Vue的声明周期函数 beforeDestroy() 中清除定时器。

代码实现:

<script>
export default {
  data() {
    return {
      time: null, //定义setInterval的定时器名称
      setTime: null //定义setTimeout的定时器名称
    }
  },
  methods: {
    // 微信支付扫码
    weChatScan(paymentPluginId, sn) {
      // 请求
      wechatSubmit({
        paymentPluginId: paymentPluginId,
        sn: sn
      })
        .then((res) => {
          return 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        })
        .then((data) => {
          this.imgUrl = data //二维码
          this.dialogVisible = true
          // 启动定时器
          this.time = setInterval(() => {
            // 判断是否支付成功
            wechatnotify({
              sn: sn
            }).then((res) => {
              if (res.data.type == 'success') {
                this.time && this.clearTimer() //清除定时器
                this.dialogVisible = false
                this.$router.push({ path: '/financialInfo' })
              }
            })
          }, 1000)
          // 5分钟后关闭模态框、清除定时器
          this.setTime = setTimeout(() => {
            this.clearTimer()
            this.dialogVisible = false
          }, 5 * 60 * 1000)
        })
    },
    //清除定时器
    clearTimer() {
      clearInterval(this.time)
      clearTimeout(this.setTime)
      this.time = null
      this.setTime = null
    },
    // 关闭模态框前
    handleClose() {
      this.imgUrl = ''
      this.clearTimer()
    }
  },
  // beforeDestroy()生命周期内清除定时器
  beforeDestroy() {
    clearInterval(this.time)
    clearTimeout(this.setTime)
    this.time = null
    this.setTime = null
  }
}
</script>

标签:定时器,清除,轮询,Vue,setTime,time,null,data
来源: https://blog.csdn.net/Windyluna/article/details/114843571