Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda