skip to Main Content

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


  1. 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:

        <script setup lang="ts">
    import { onUnmounted } from "vue";
    
    let timerId = setInterval(() => {
      // Your code here
      console.log("Timer is running...");
    }, 1000);
    
    onUnmounted(() => {
      clearInterval(timerId);
    });
    </script>
    
    Login or Signup to reply.
  2. If you can use libs, use libs
    https://vueuse.org/shared/useIntervalFn/

    import { useIntervalFn } from '@vueuse/core'
    
    const { pause, resume, isActive } = useIntervalFn(() => {
      /* your function */
    }, 1000)
    

    Otherwise, make a composable

    function useIntervalFn(cb: () => void, ms: number) {
       let int: number = 0;
       onMounted(() => int = setInterval(cb, ms));
       onUnmounted(() => clearInterval(int));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search