Solve the problem that setInterval empty timer does not work in js

  • 2021-09-20 19:30:28
  • OfStack

Usage scenario: I call the timer function in the function A, and the timer is a function written separately

Reason: I called the function A once when the page loaded, and then called the timer function once separately, resulting in setInterval () being called twice, resulting in setInterval_id having two values.

Problems found by printing the value of the timer.

clearInterval () shuts down only one of the setInterval_id, and the other setInterval_id also starts setInterval ().

Solution: Remove the timer function called separately.

Additional knowledge: setTimeout in js vue cannot clear the problem through clearTimeout

In asynchronous cleanup, when the identity of setTimeout stored in data in vue is used for cleanup, it cannot be cleaned. You need to prefix the function with window

Such as window. setTimeout and window. clearTimeout

The specific code is as follows

Simplified code.

The environment is electron-vue. The rendering process asynchronously acquires html from the main process and renders it to the page, and the display of loading is needed in the process.

this. timeOutLoading events are always triggered when window is not added to setTimeout and clearTimeout.


<template>
<div id="dev">
    <el-tabs v-model="activeName" @tab-click="handleClick" v-loading="loading">
    <el-tab-pane label=" Document " name="first">
      <div v-html="html"></div>
    </el-tab-pane>
     <el-tab-pane label=" Settings " 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;'> Loading ...</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;'> Load timeout </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>

Related articles: