欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

解决js中的setInterval清空定时器不管用问题

时间:2021-03-02 11:48:05|栏目:JavaScript代码|点击:

使用场景:我在函数A中调用定时器函数,定时器是单独写的一个函数

原因:页面加载时我调用了1次函数A,然后又单独调用了一次定时器函数,导致调用了2次setInterval(),导致有setInterval_id有2个值。

通过打印定时器的值发现的问题。

clearInterval()只关闭了其中一个setInterval_id,另一个setInterval_id还会启动setInterval()。

解决方法:把单独调用的定时器函数去掉。

补充知识:js vue中setTimeout无法通过clearTimeout清除问题

在异步清除中,利用vue 中data存放setTimeout的标识进行清除时,无法清除。则需要在函数前加上window.即可

如window.setTimeout与window.clearTimeout

具体代码如下

精简后的代码。

环境为electron-vue 渲染进程异步获取主进程上html并渲染到页面、过程中需要有loading的显示。

setTimeout 与clearTimeout 未加window时,this.timeOutLoading事件总会被触发。

<template>
<div id="dev">
    <el-tabs v-model="activeName" @tab-click="handleClick" v-loading="loading">
    <el-tab-pane label="文档" name="first">
      <div v-html="html"></div>
    </el-tab-pane>
     <el-tab-pane label="设置" name="second">
      <v-devCard></v-devCard>
    </el-tab-pane>
    </el-tabs>
</div>
</template>

<script>
  const {ipcRenderer:ipc} = require('electron');

export default {

  data(){
    return{
      activeName: 'second',
      html:'',
      loading:false,
      timeOutLoading:0
    }
  },
  methods:{
    handleClick(tab, event) {
    if(tab.name == 'first' && this.loading == false){
      if(this.timeOutLoading != 0){
        window.clearTimeout(this.timeOutLoading);
      }

      this.html = "<div style='text-align:center; height:200px; line-height:200px;'>加载中...</div>";
      this.loading = true;
      this.timeOutLoading = window.setTimeout(() => {
        if(this.loading == true){
          this.loading = false;
          this.html = "<div style='text-align:center; height:200px; line-height:200px;'>加载超时</div>";
        } 
      }, 3000);

      window.setTimeout(() => {
        ipc.send("getPage");
      }, 500);
       
    }
   }
  },
  mounted(){
    ipc.on('getPage-reply', (event, arg) => {
        if(this.timeOutLoading != 0){
          window.clearTimeout(this.timeOutLoading);
          this.timeOutLoading = 0;
        }      
        this.loading = false;
        this.html = arg; 
      });
  }
}
</script>

上一篇:js倒计时小实例(多次定时)

栏    目:JavaScript代码

下一篇:深入理解ES6的迭代器与生成器

本文标题:解决js中的setInterval清空定时器不管用问题

本文地址:http://www.codeinn.net/misctech/73000.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有