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.
npm install vue-timer-hookVerified import paths — ran on the pinned version, not inferred.
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`.
Ensure your project is using Vue 3 and that components are structured with the Composition API (e.g., `<script setup>`).
Always append `.value` when reading or writing to reactive properties returned by the hooks, for example: `if (timer.isExpired.value) { /* ... */ }`.Always initialize `useTimer` with a valid `new Date()` object, ensuring its seconds/minutes are correctly set, or a valid numeric timestamp. For example: `new Date(Date.now() + 60000)` for one minute.
When calling `timer.restart()`, pass a newly created `Date` object, e.g., `timer.restart(new Date(Date.now() + 5 * 60 * 1000))`. For `useStopwatch.restart()`, simply call `stopwatch.restart()` without arguments to reset it.
Use a unique `:key` prop on components using these hooks when they are part of a `v-for` loop or conditionally rendered with `v-if` to ensure proper component lifecycle and re-initialization. For example: `<MyTimerComponent v-if="showTimer" :key="uniqueId" />`.
Access reactive properties using `.value`, for instance: `timer.isRunning.value` or `timer.seconds.value`.
Ensure your Vue component uses `<script setup lang='ts'>` and your project is configured for Vue 3.
Ensure `useTimer` is initialized with a properly constructed `new Date()` object, for example: `const time = new Date(); time.setSeconds(time.getSeconds() + 300);`.