Search code examples
javascriptreact-nativecountdowntimer

React Native: Timer keeps reseting


I am trying to do a countdown timer but after it gets to 1 it resets to 5 when its supposed to go to '00:00', I don't know where I am going wrong please may someone help me

This is my code:

const CountDown = () => {
    const RESET_INTERVAL_S = 5;

    const formatTime = (time) =>
        `${String(Math.floor(time / 60)).padStart(2, "0")}:${String(
            time % 60
        ).padStart(2, "0")}`;

    const Timer = ({ time }) => {
        const timeRemain = RESET_INTERVAL_S - (time % RESET_INTERVAL_S);

        return (
            <>
                <Text>{formatTime(timeRemain)}</Text>
            </>
        );
    };

    const IntervalTimerFunctional = () => {
        const [time, setTime] = useState(0);

        console.log("The time is", time);

        useEffect(() => {
            const timerId = setInterval(() => {
                setTime((t) => t + 1);
            }, 1000);
            return () => clearInterval(timerId);
        }, []);

        return <Timer time={time} />;
    };

    return <IntervalTimerFunctional />;
};


Solution

  • I am not sure this is a perfect solution but this could work:

    You could stop your timer when it reaches its maximum value:

     useEffect(() => {
        const timerId = setInterval(() => {
            setTime((t) => {
                if(t + 1 === RESET_INTERVAL_S) {
                    clearInterval(timerId)
                }
    
                return t + 1;
            });
        }, 1000);
    
        return () => clearInterval(timerId);
    
    }, []);
    

    And display "00:00" when you have reached the limit:

        <Text>{time === RESET_INTERVAL_S ? "00:00" : formatTime(timeRemain)}</Text>
    

    Here is a working example