溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

在JavaScript中使用setInterval無(wú)法清空定時(shí)器如何解決

發(fā)布時(shí)間:2020-11-19 15:34:38 來(lái)源:億速云 閱讀:660 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

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

使用場(chǎng)景:我在函數(shù)A中調(diào)用定時(shí)器函數(shù),定時(shí)器是單獨(dú)寫(xiě)的一個(gè)函數(shù)

原因:頁(yè)面加載時(shí)我調(diào)用了1次函數(shù)A,然后又單獨(dú)調(diào)用了一次定時(shí)器函數(shù),導(dǎo)致調(diào)用了2次setInterval(),導(dǎo)致有setInterval_id有2個(gè)值。

通過(guò)打印定時(shí)器的值發(fā)現(xiàn)的問(wèn)題。

clearInterval()只關(guān)閉了其中一個(gè)setInterval_id,另一個(gè)setInterval_id還會(huì)啟動(dòng)setInterval()。

解決方法:把單獨(dú)調(diào)用的定時(shí)器函數(shù)去掉。

補(bǔ)充知識(shí):js vue中setTimeout無(wú)法通過(guò)clearTimeout清除問(wèn)題

在異步清除中,利用vue 中data存放setTimeout的標(biāo)識(shí)進(jìn)行清除時(shí),無(wú)法清除。則需要在函數(shù)前加上window.即可

如window.setTimeout與window.clearTimeout

具體代碼如下

精簡(jiǎn)后的代碼。

環(huán)境為electron-vue 渲染進(jìn)程異步獲取主進(jìn)程上html并渲染到頁(yè)面、過(guò)程中需要有l(wèi)oading的顯示。

setTimeout 與clearTimeout 未加window時(shí),this.timeOutLoading事件總會(huì)被觸發(fā)。

<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="設(shè)置" 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;'>加載超時(shí)</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>

關(guān)于在JavaScript中使用setInterval無(wú)法清空定時(shí)器如何解決就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI