iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue中定时器setInterval的使用及说明
  • 190
分享到

vue中定时器setInterval的使用及说明

vue定时器vuesetInterval使用vue定时器setInterval 2023-03-02 20:03:53 190人浏览 泡泡鱼
摘要

目录深坑声明销毁that 是指Vue , this是指定时器 positionTimer总结深坑 自己在项目中使用setInterval,由于不正确的使用,竟然导致了浏览器崩溃,项目

深坑

自己在项目中使用setInterval,由于不正确的使用,竟然导致了浏览器崩溃,项目停止,电脑死机…可怕之极,下面详细写一下关于定时器的用法及注意事项

声明

    mouted() {
    	this.timer = setInterval(()=>{
    	// 要执行的函数
    	})
    }

销毁

destoryed() {
	this.clearInterval(this.timer)
}

看起来是很简单也没有什么,但是坑来了,实际项目中使用

在这里插入图片描述

    addSetInterval() {
      const that = this
      this.positionTimer = setInterval(() => {
        if (that.resultArr.length < that.times) {
          clearInterval(that.positionTimer)
          that.positionTimer = null
          console.log(that.times)
        } else {
          // 分批部署基站
          if (that.times < that.resultArr.length) {
            that.deployBaseStation()
            console.log('渲染数组的第' + that.times + '项')
          }
          that.times++
        }
        console.log(1111111111111)
      }, 500)
    },

由于这里定义了定时器,箭头函数内部和外部的作用域不同了,要定义一个变量来使函数内部使用vue数据的时候指向不出错,

that 是指vue , this是指定时器 positionTimer

之前为了确认定时器已经停止了,在destory中和定时器中都输出了定时器的值,即 console.log(this.positionTimer),然而,上图

在这里插入图片描述

离开当前路由,再回到当前路由,之后控制台打印

在这里插入图片描述

然后不久之后就是

在这里插入图片描述

WTF???

在请教了同学之后,她说可能跟我打印定时器也有关系,输出的时候调用了定时器,导致定时器关闭失败,我也是真的无奈了,一开始也没有定义额外的变量来确定this的指向,具体原因不明,总之,在不输出定时器,改加了额外的变量之后,定时器停止了

最终代码如下:

  destroyed() {
    clearInterval(this.positionTimer)// 清除定时器
    this.positionTimer = null
    // 离开路由之后断开websocket连接
    this.WEBSocketOnClose()
    this.websocketclose()
  },
  methods: {
    // 添加定时器
    addSetInterval() {
      const that = this  // 声明一个变量指向vue实例this,保证作用域一致
      this.positionTimer = setInterval(() => {
        if (that.resultArr.length < that.times) {
          clearInterval(that.positionTimer)
          that.positionTimer = null
          console.log(that.times)
        } else {
          // 分批部署基站
          if (that.times < that.resultArr.length) {
            that.deployBaseStation()
            console.log('渲染数组的第' + that.times + '项')
          }
          that.times++
        }
        console.log(1111111111111)
      }, 500)
    },

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: vue中定时器setInterval的使用及说明

本文链接: https://www.lsjlt.com/news/198296.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作