Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda