Fully functioning countdown timer using React hooks only

Here’s my code. You can also check it out on Stackblitz:

import React, { useState } from 'react';

const Timer = ({
    initialHours = 10,
    initialMinutes = 0,
    initialSeconds = 0,
}) => {
    const [hours, setHours] = useState(initialHours);
    const [minutes, setMinutes] = useState(initialMinutes);
    const [seconds, setSeconds] = useState(initialSeconds);

    let myInterval;

    const startTimer = () => {
        myInterval = setInterval(() => {
            if (seconds > 0) {
                setSeconds(seconds - 1);
            }
            if (seconds === 0) {
                if (hours === 0 && minutes === 0) {
                    clearInterval(myInterval);
                } else if (minutes > 0) {
                    setMinutes(minutes - 1);
                    setSeconds(59);
                } else if (hours > 0) {
                    setHours(hours - 1);
                    setMinutes(59);
                    setSeconds(59);
                }
            }
        }, 1000);
        cancelTimer();
    };
    const cancelTimer = () => {
        return () => {
            clearInterval(myInterval);
        };
    };

    return (
        <div>
            <h1 className='timer'>
                {hours < 10 && hours !== 0 ? `0${hours}:` : hours >= 10 && `${hours}:`}
                {minutes < 10 ? `0${minutes}` : minutes}:
                {seconds < 10 ? `0${seconds}` : seconds}
            </h1>
            <button onClick={startTimer}>START</button>
            <button>PAUSE</button>
            <button>RESUME</button>
            <button onClick={cancelTimer}>CANCEL</button>
        </div>
    );
};

export default Timer;

I’m having trouble with the START button and this is what it looks like when I click on the START button multiple times:
enter image description here

You’ll notice that on the first click the number never continues to go down unless I click on the START button again and again but it would look like a broken slot machine. And if I hit on the CANCEL button, it should stop the timer and reset back to the set time, but it doesn’t. I don’t know how to solve the problem for this 2 buttons, and much more for the PAUSE and RESUME. I don’t know how to make them work, too. Please help.

21 thoughts on “Fully functioning countdown timer using React hooks only”

  1. 76237 470598Excellently written post, doubts all bloggers offered exactly the same content because you, the internet can be a greater spot. Please keep it up! 135590

    Reply

Leave a Comment