SoFunction
Updated on 2025-04-04

Vue3 setup syntax sugar destroys one or more timers (setTimeout/setInterval)

background

If a timer is added to the page/component, even if you jump to other pages, the timer will not be cleaned. At this time, you need to clean it manually, otherwise there will be unexpected bugs and will also affect performance.

hint

setTimeout is executed only once, and setInterval is executed loop. The following is an example of using setTimeout. If you want to use setInterval, just replace the method once.

  • Replace setTimeout with setInterval
  • Replace clearTimeout with clearInterval

Destroy a timer

<script setup>
import {onMounted, onUnmounted} from "vue";

//Note, this is emptyconst timer = ref()

// Create a timer firstonMounted(() => {
  =setTimeout(() => {
    // do something
  }, 1500)
})

//Destroy the timer before the page is destroyedonUnmounted(() => {
  clearTimeout()
  =""
})

Destroy multiple timers

<script setup>
import {onMounted, onUnmounted} from "vue";

//Note that it is an array, not an object, of course it is OK to use the object methodconst timer = ref([])

//Create several timers firstonMounted(() => {
  (setTimeout(() => {
    // do something
  }, 1500))
  (setTimeout(() => {
    // do something
  }, 1800))
})

//Destroy the timer before the page is destroyedonUnmounted(() => {
  for (const timerElement of ) {
    clearTimeout(timerElement)
  }
  =[]
})

Added: To setTimeout point to the correct value, you can use the following method:

1. Use arrow function

export default {
 methods: {
  start: function () {
   setTimeout(() => {
    ()//The doll disappears   }, 4000);
  }
 }
}

At this time, this function points to the object when defining it, that is, this points to the corresponding variable in data.

Summarize

This is the article about Vue3 setup syntax sugar destroying one or more timers (setTimeout/setInterval). For more related contents of Vue3 setup syntax sugar destroying timers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!