Files
cz-web/src/composables/useCountDown.ts
2026-10-01 17:24:57 +08:00

32 lines
677 B
TypeScript

import { computed, onScopeDispose, ref } from 'vue'
export function useCountDown(defaultSeconds = 60) {
const seconds = ref(0)
let timer: ReturnType<typeof setInterval> | null = null
const isCounting = computed(() => seconds.value > 0)
function start(total: number = defaultSeconds): void {
reset()
seconds.value = total
timer = setInterval(() => {
seconds.value -= 1
if (seconds.value <= 0) {
reset()
}
}, 1000)
}
function reset(): void {
if (timer !== null) {
clearInterval(timer)
timer = null
}
seconds.value = 0
}
onScopeDispose(reset)
return { seconds, isCounting, start, reset }
}