Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Countdown Timer using functional component in ReactJS doesn't work properly

I want to make a countdown timer with start, stop, resume and reset buttons. However, I could not figure out why my code does not work. I am guessing that the issue lies in the part on timer, setInterval and clearInterval.

I have attached snippets of my code below.

Help would be greatly appreciated, thanks!

function Countdown() {

    const [ timerRunning, setTimerRunning ] = useState(false);
    const [ startTime, setStartTime ] = useState(0);
    const [ totalTime, setTotalTime ] = useState(0);

    var timer;

    const startTimer = () => {
        setTimerRunning(true);
        setStartTime(totalTime);
        setTotalTime(totalTime);
        
        timer = setInterval(() => {
            const remainingTime = totalTime - 1000;
            if (remainingTime >= 0) {
                setTotalTime(remainingTime);
            } else {
                clearInterval(timer);
                setTimerRunning(false);
                setStartTime(0);
                setTotalTime(0);
            }
        }, 1000);
    };

    const stopTimer = () => {
        clearInterval(timer);
        setTimerRunning(false);
    };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

you have to put your setInterval in React.useEffect take a look at this post some suggestions for your code:

  • use className instead of class attribute in your elements.
  • don't use var or let in react functional components.
about 4 years ago · Juan Pablo Isaza Report

0

useState doesn't change value immediately. So it's value is not actually changing. To avoid this use UseEffect hook.

useEffect(() => {
        let intervalid
      if (timerRunning){
          intervalid = setInterval(() => {
            const remainingTime = totalTime - 1000;
            if (remainingTime >= 0) {
                
                setTotalTime(remainingTime);
            } else {
                clearInterval(intervalid);
                setTimerRunning(false);
                setStartTime(0);
                setTotalTime(0);
            }
          }, 1000);
      }

    
      return () => {
        clearInterval(intervalid)
      }
    }, [timerRunning,totalTime]) 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!