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

192
Views
Javascript clearInterval with interval Id doesn't work in react js

I implemented a timer which works fine but the only problem is that it doesn't clearInterval when the timer ends .

My code looks like this :

  const [currentCount, setCurrentCount] = React.useState(10);
  const [intervalId, setIntervalId] = React.useState(10);

  React.useEffect(() => {
    const intervalId = setInterval(timer, 1000);
    // store intervalId in the state so it can be accessed later:
    setIntervalId(intervalId);
    return () => {
      clearInterval(intervalId);
    };
  }, []);

  const timer = () => {
    setCurrentCount((prev) => {
      if (prev > 0) {
        return prev - 1;
      } else if (prev === 0) {
        console.log("Still Runs");
        clearInterval(intervalId);
        return prev;
      }
    });
  };

The value of currentCount decreases from 10 to 0 but I want to clear the interval when it reaches 0 and I tried to clear it with this piece of code clearInterval(intervalId) but didn't work .

How can I clearInterval when the value of currentCount reaches 0 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your useEffect hook is missing an important dependency from its dependency array: timer. To make things simpler on yourself, you can move the timer variable inside the effect (unless you have a good reason for it to be outside). This ends up having the added bonus that the timer function will be able to reference the interval ID without maintaining it in state.

const [currentCount, setCurrentCount] = React.useState(10);

React.useEffect(() => {
  const timer = () => {
    setCurrentCount((prev) => {
      if (prev > 0) {
        return prev - 1;
      } else if (prev === 0) {
        console.log("Still Runs");
        clearInterval(intervalId);
        return prev;
      }
    });
  };
  const intervalId = setInterval(timer, 1000);

  return () => {
    clearInterval(intervalId);
  };
}, []);
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!