Open menu dropdown
useTimer
A reactive countdown that you can start, pause, resume, stop and reset, with the remaining time in ms and a callback at the end - for an auto close, a resend delay or a quiz timer.
The composable provides the following functionality:
- start: Starts the timer, which decrements the remaining time every
remainingTimeUpdatems (200 by default) until it reaches 0, then runs the callback.start(ms)changes the timeout. - pause: Pauses the active timer, allowing it to be resumed later from the point it was paused.
- resume: Resumes the timer from the point it was paused, considering the remaining time.
- stop: Stops the timer and resets the remaining time to the timeout.
- reset: Resets the remaining time to the timeout, without stopping the timer.
- remainingTime: A reactive variable that holds the current remaining time in milliseconds. It updates reactively as the timer progresses.
The timer is stopped when the component is unmounted (or the effectScope stopped): the callback never runs after it.
This composable can be used in Vue components to handle timeouts in a flexible and reactive manner.
Usage
Remaning time: 4000ms
vue
<script lang="ts" setup>
import { useTimer, useToast } from 'maz-ui/composables'
const toast = useToast()
const { start, stop, pause, resume, remainingTime } = useTimer({
timeout: 4000,
callback: () => toast.info('Timeout end', {
button: {
onClick: start,
text: 're-start',
closeToast: true,
},
})
})
</script>
<template>
<MazBtn @click="start">
Start
</MazBtn>
<MazBtn color="destructive" @click="stop">
Stop
</MazBtn>
<MazBtn color="warning" @click="pause">
Pause
</MazBtn>
<MazBtn color="secondary" @click="resume">
Resume
</MazBtn>
</template>Set timeout with start function
Starts the timer with the specified timeout. If the timeout is not provided, it uses the default value of 1000ms.
ts
const { start } = useTimer()
start(4000)Types
ts
export interface TimerOptions {
/**
* The time in milliseconds
* @default 1000
*/
timeout?: number
/**
* The callback to execute when the timer is finished
* @default undefined
*/
callback?: () => unknown
/**
* The interval to update the remaining time
* @default 200
*/
remainingTimeUpdate?: number
/**
* The offset time to execute the callback
* @default 0
*/
callbackOffsetTime?: number
}