I’m writing an application which uses a timer to update variables every second. It uses "setInterval" function to start the timer, and uses "clearInterval" function to stop it. And I don’t think I have a good enough way of doing this.
I tried to define the timer as a ref variable in setup function, and clear the timer in the "onUnmounted" lifecycle hook, like the example code below:
<script setup lang="ts">
import { ref, onUnmounted } from "vue";
const timer = ref(setInterval(() => {/* Bla bla bla. */}, 1000));
onUnmounted(() => {
clearInterval(timer.value);
})
<script>
But I don’t think it would be necessary to make the timer reactive, is there a better way of doing this? Or is my code a good method?
2
Answers
Your approach is a good way to handle timers in a Vue application. However, as you mentioned, making the timer reactive is not necessary in this case. Instead, you can directly assign the timer ID to a variable. Here’s an example of how you can improve your code:
If you can use libs, use libs
https://vueuse.org/shared/useIntervalFn/
Otherwise, make a composable