useCountdown.ts
956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { ref, unref } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';
export function useCountdown(count: number) {
const currentCount = ref(count);
const isStart = ref(false);
let timerId: ReturnType<typeof setInterval> | null;
function clear() {
timerId && window.clearInterval(timerId);
}
function stop() {
isStart.value = false;
clear();
timerId = null;
}
function start() {
if (unref(isStart) || !!timerId) {
return;
}
isStart.value = true;
timerId = setInterval(() => {
if (unref(currentCount) === 1) {
stop();
currentCount.value = count;
} else {
currentCount.value -= 1;
}
}, 1000);
}
function reset() {
currentCount.value = count;
stop();
}
function restart() {
reset();
start();
}
tryOnUnmounted(() => {
reset();
});
return { start, reset, restart, clear, stop, currentCount, isStart };
}