溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在JavaScript中使用setInterval無法清空定時器如何解決

發布時間:2020-11-19 15:34:38 來源:億速云 閱讀:720 作者:Leah 欄目:開發技術

這篇文章給大家介紹在JavaScript中使用setInterval無法清空定時器如何解決,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

使用場景:我在函數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>

關于在JavaScript中使用setInterval無法清空定時器如何解決就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女