Files
dmenu-plus-front/src/hooks/useCountdown.ts
T
2025-06-30 23:02:12 +03:30

52 lines
1.4 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
export const useCountdown = (shouldStart: boolean, duration: number = 30, delay: number = 1000) => {
const [timerRunning, setTimerRunning] = useState(false);
const [secondsLeft, setSecondsLeft] = useState(duration);
const intervalRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (shouldStart) {
setSecondsLeft(duration);
setTimerRunning(true);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shouldStart]);
const stop = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
const restart = () => {
stop();
setSecondsLeft(duration);
setTimerRunning(true);
}
useEffect(() => {
if (timerRunning && intervalRef.current === null) {
intervalRef.current = setInterval(() => {
setSecondsLeft((prev) => {
if (prev <= 1) {
setTimerRunning(false);
clearInterval(intervalRef.current!);
intervalRef.current = null;
return 0;
}
return prev - 1;
});
}, delay);
}
return () => {
stop();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timerRunning]);
return { timerRunning, secondsLeft, setTimerRunning, setSecondsLeft, stop, restart };
};