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 system prohibits remote login command of root account

ps: Here is how to disable remote login of root a...

MySQL 8.0.22 decompression version installation tutorial (for beginners only)

Table of contents 1. Resource download 2. Unzip t...

SQL implements LeetCode (180. Continuous numbers)

[LeetCode] 180. Consecutive Numbers Write a SQL q...

Example of how to quickly delete a 2T table in mysql in Innodb

Preface This article mainly introduces the releva...

Docker installation and deployment of Net Core implementation process analysis

1. Docker installation and settings #Install Cent...

Some points on using standard HTML codes in web page creation

The most common mistake made by many website desi...

Detailed steps to install VMware Tools from scratch (graphic tutorial)

VMware Tools is a tool that comes with VMware vir...

Apache Bench stress testing tool implementation principle and usage analysis

1: Throughput (Requests per second) A quantitativ...

Download MySQL 5.7 and detailed installation diagram for MySql on Mac

1. Enter the following address in the browser htt...

Summary of pitfalls of using nginx as a reverse proxy for grpc

background As we all know, nginx is a high-perfor...

Summary of 50+ Utility Functions in JavaScript

JavaScript can do a lot of great things. This art...

MySQL learning database search statement DQL Xiaobai chapter

Table of contents 1. Simple retrieval of data 2. ...