Create useTimer composable

This commit is contained in:
marzban-dev
2024-12-30 19:55:52 +03:30
parent bf95002a41
commit 47947419c6
+42
View File
@@ -0,0 +1,42 @@
type Props = {
duration: number;
callback?: () => void
}
export function useTimer({ duration, callback }: Props) {
const timeout = ref<NodeJS.Timeout | null>(null);
const interval = ref<NodeJS.Timeout | null>(null);
const isPending = ref(false);
const timer = ref(duration / 1000);
const reset = () => {
if (timeout.value) clearTimeout(timeout.value);
if (interval.value) clearInterval(interval.value);
isPending.value = false;
timer.value = duration / 1000;
};
const start = () => {
isPending.value = true;
timeout.value = setTimeout(() => {
if (interval.value) clearInterval(interval.value);
if (callback) callback();
isPending.value = false;
timer.value = duration / 1000;
}, duration);
interval.value = setInterval(() => {
timer.value -= 1;
}, 1000);
};
return {
isPending,
timer,
reset,
start
};
}