Vue Timer Hook

1.0.86 · active · verified Sun Apr 19

Vue Timer Hook is a Vue 3 composition API library providing reactive hooks for common time-based functionalities within components. It offers `useTimer` for countdowns, `useStopwatch` for tracking elapsed time, and `useTime` for continuously retrieving the current time. Currently at version 1.0.86, the library demonstrates a positive version release cadence, with the last publish occurring 3 months ago, indicating active maintenance. Its primary benefit lies in simplifying time-related state management in Vue components, abstracting away complex `setInterval` and `clearInterval` logic, and providing a clean, reactive interface. It is purpose-built for the Vue 3 ecosystem and the Composition API, making it a direct fit for modern Vue projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a 10-minute countdown timer using `useTimer`, control it with start, pause, resume, and restart functions, and react to its expiration. It also highlights accessing reactive properties with `.value`.

<template>
  <div>
    <h1>Vue Timer Hook Demo</h1>
    <p>Countdown Timer:</p>
    <div>
      <span>{{ timer.days }}</span>:<span>{{ timer.hours }}</span>:<span>{{ timer.minutes }}</span>:<span>{{ timer.seconds }}</span>
    </div>
    <p>{{ timer.isRunning.value ? 'Running' : 'Not running' }}</p>
    <button @click="timer.start()">Start</button>
    <button @click="timer.pause()">Pause</button>
    <button @click="timer.resume()">Resume</button>
    <button @click="restartFive()">Restart to 5 minutes</button>
  </div>
</template>

<script setup lang="ts">
  import { watchEffect, onMounted, ref } from 'vue'
  import { useTimer } from 'vue-timer-hook'

  // Set an initial 10-minute timer
  const initialTime = new Date()
  initialTime.setSeconds(initialTime.getSeconds() + 600) // 10 minutes

  const timer = useTimer(initialTime, { autoStart: true })

  const restartFive = () => {
    // Restarts to a new 5-minute timer
    const newTime = new Date()
    newTime.setSeconds(newTime.getSeconds() + 300)
    timer.restart(newTime)
  }

  onMounted(() => {
    // Watch for the timer to expire
    watchEffect(() => {
      if (timer.isExpired.value) {
        console.log('Timer has expired!')
        // You could trigger an action here, e.g., show a message
      }
    })
  })
</script>

view raw JSON →