diff --git a/frontend/composables/useTimer.ts b/frontend/composables/useTimer.ts new file mode 100644 index 0000000..5f6b943 --- /dev/null +++ b/frontend/composables/useTimer.ts @@ -0,0 +1,42 @@ +type Props = { + duration: number; + callback?: () => void +} + +export function useTimer({ duration, callback }: Props) { + const timeout = ref(null); + const interval = ref(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 + }; +} \ No newline at end of file