How to clear the timer elegantly in Vue

How to clear the timer elegantly in Vue

Preface

Clear the timer. I believe quite a few people write it like this:

export default {
  data() {
    reurn
      timer: null
    }
  },
  
  mounted() {
    this.timer = setInterval(() => {
      console.log('setInterval')
    }, 2000)
  },
  
  beforeDestroy() {
    clearInterval(this.timer)
  }
}

This is a common piece of code. At least several of my friends (with 1-3 years of experience) write it this way. There are three inelegant problems here:

  • After clearInterval, the timer is not cleared and is null.
  • The code for starting and clearing the timer is spread across two places, which hurts readability/maintainability. In the words of You Dada, it makes it harder to programmatically clean up what we’ve built.
  • The timer is defined in the data. In fact, the timer does not require any responsive operation. It is unnecessary to define it in the data, which will cause performance waste.

optimization

Directly on the code:

export default {
  data() {
    reurn
    }
  },
  
  mounted() {
    let timer = setInterval(() => {
      console.log('setInterval')
    }, 2000)
    this.$once('hook:beforeDestroy', () => {
      clearInterval(timer)
      timer = null
    })
  }
}

Here, a hook is used to monitor the beforeDestroy life cycle, so that the timer only needs to be defined in the life cycle, and all the above problems are solved.

Derivative question: beforeDestroy is not triggered?

In the backend system, we often set up page caches. When the route is cached by keep-alive, the beforeDestroy life cycle is not followed. Therefore, some people think that clearing the timer in beforeDestroy is enough, and they don’t even check that the timer is not actually cleared. Knowing the reason is easy to solve, with the help of activated and deactivated hooks:

export default {
  data() {
    reurn
    }
  },
  
  mounted() {
    let timer = setInterval(() => {
      console.log('setInterval')
    }, 2000)
    this.$on('hook:activated', () => {
      if (timer === null) { // Avoid repeated timer activation timer = setInterval(() => {
          console.log('setInterval')
        }, 2000)
      }
    })
    this.$on('hook:deactivated', () => {
      clearInterval(timer)
      timer = null
    })
  }
}

It should be noted here that due to caching reasons, $on should be used instead of $once, otherwise it will not be triggered again after being executed once.

This is the end of this article about how to elegantly clear the timer in Vue. For more relevant Vue clearing timer content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to set and clear timers in Vue
  • Vue implements vertical scrolling announcement through timer
  • Vue (timer) solves the problem that mounted cannot obtain data in data
  • Solution to Vue setInterval timer failure
  • How to destroy the timer when leaving the vue page

<<:  Detailed steps to install a virtual machine and use CentOS 8 using VMware 15

>>:  Monitor changes in MySQL table content and enable MySQL binlog

Recommend

Linux five-step build kernel tree

Table of contents 0. The kernel tree that comes w...

Complete steps to use samba to share folders in CentOS 7

Preface Samba is a free software that implements ...

How to implement second-level scheduled tasks with Linux Crontab Shell script

1. Write Shell script crontab.sh #!/bin/bash step...

Detailed explanation of the use of CSS3 rgb and rgba (transparent color)

I believe everyone is very sensitive to colors. C...

How to set static IP for Ubuntu 18.04 Server

1. Background Netplan is a new command-line netwo...

Detailed explanation of MYSQL large-scale write problem optimization

Abstract: When people talk about MySQL performanc...

Vue component library ElementUI implements table loading tree data tutorial

ElementUI implements a table tree list loading tu...

Example of using #include file in html

There are two files a.htm and b.htm. In the same d...

How to implement batch deletion of large amounts of data in MySQL large tables

The question is referenced from: https://www.zhih...

TypeScript interface definition case tutorial

The role of the interface: Interface, in English:...

js uses Canvas to merge multiple pictures into one implementation code

Solution function mergeImgs(list) { const imgDom ...

Understanding and using React useEffect

Table of contents Avoid repetitive rendering loop...

Ubuntu 20.04 firewall settings simple tutorial (novice)

Preface In today's increasingly convenient In...

js to realize the mouse following game

This article shares the specific code of js to im...