Vue 使用setInterval定时器导致前端页面卡死(解决方法)

Vue 使用setInterval定时器导致前端页面卡死

在这里插入图片描述

在这里插入图片描述

原因

setinterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,最终卡死你的网页。
其原因与JS引擎线程有关(需深入研究JS引擎线程) ,但是setTimeout是自带清除定时器的。

解决方案

  mounted() {
    
    
    this.getList();
    if (this.timer) {
    
    
      clearInterval(this.timer);
    } else {
    
    
      this.timer = setInterval(() => {
    
    
        setTimeout(this.getList(), 0);
        // console.log("刷新" + new Date());
      }, 10000);
    }
    this.$once("hook:beforeDestroy", () => {
    
    
      clearInterval(this.timer);
    });
  },

猜你喜欢

转载自blog.csdn.net/Maxueyingying/article/details/139735476