Vue使用定时器setInterval页面跳转后定时器叠加的问题

需求:每次进入指定页面后,每隔5分钟自动刷新列表数据,代码如下

created() {
    this.periodicRefresh()
},
methods:{
    //查询当前出票中数据
    getTicketData(){
      console.log("定时器"+this.timer);
      let res = {
          per_page: this.per_page, //不传默认25
          page: this.nowPages,
          type: 2,
          query_start_time: "",
          query_end_time: "",
          oid: "",
          mobile: "",
          pin_search: "",
          cinema_set:1,
        };
      get_movie(res).then((response) => {
        if(response.code==200){
          this.ticketData = response.data.count;
        }
      }).catch((err) => {});
    },
    //定时刷新列表
    periodicRefresh(){
      this.getTicketData()
      clearInterval(this.timer)
      this.timer=setInterval(this.getTicketData,300000)
    },
}    

问题:当项目跳转另外一个页面,再次回到当前页面时,会产生多个定时器,导致列表刷新时间越来越近

原因:setInterval属于全局方法,当我们停在当前页面时,会产生一个定时器,从其他页面再次回到当前页面时,会再次产生定时器,而之前的定时器,实际上并没有被销毁(虽然在定时器之前调用了清除方法,而实际上,页面刷新回来时,this.timer 是"",因为this.timer属于当前页面的变量,而已经产生的定时器是全局变量,所以并没有清理掉已经产生的定时器)

//定时刷新列表
periodicRefresh(){
  this.getTicketData()
  clearInterval(this.timer)//这里虽然在定时器之前调用了清除方法,而实际上,页面刷新回来时,this.timer 是"",因为this.timer属于当前页面的变量,而已经产生的定时器是全局变量,所以并没有清理掉已经产生的定时器
  this.timer=setInterval(this.getTicketData,300000)
},

所以,修改代码如下,至此问题解决 

created() {
    this.periodicRefresh()
},
beforeDestroy(){
    console.log("销毁定时器"+this.timer);
    clearInterval(this.timer)
},
methods:{
    //查询当前出票中数据
    getTicketData(){
      console.log("定时器"+this.timer);
      let res = {
        per_page: this.per_page, //不传默认25
        page: this.nowPages,
        type: 2,
        query_start_time: "",
        query_end_time: "",
        oid: "",
        mobile: "",
        pin_search: "",
        cinema_set:1,
      };
      get_movie(res).then((response) => {
          if(response.code==200){
            this.ticketData = response.data.count;
          }
        })
        .catch((err) => {});
    },
    //定时刷新列表
    periodicRefresh(){
      this.getTicketData()
      this.timer=setInterval(this.getTicketData,300000)
    },
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值