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

251
Vistas
How to check if a number is greater than another number inside useEffect

Js being difficult to me >:|

export default function Timer() {
  const [timer, setTimer] = useState(10000);

  useEffect(() => {
    setInterval(() => {
      if (Number(timer) > Number(6000)) {
        setTimer((prevCount) => prevCount - 100);
      }
    }, 100);
  }, []);
  
  console.log(timer);

Why doesn't this timer stop counting down when it hit 6000?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You wont need setInterval. Let useEffect run only when the timer changes and this is done by passing the timer as argument.

This link describe how to optimize useEffect

const [timer, setTimer] = useState(10000);

function setTimerToNewValue() {
  setTimer(timer - 100);
}

useEffect(() => {
  if (timer > 6000) {
    setTimerToNewValue();
  }
}, [timer]);
console.log(timer);

In this example useEffect will execute as soon as timer changes.

Here is another implementation with setInterval

function setTimerToNewValue() {
  setTimer((timer) => timer - 100);
}

useEffect(() => {
  let z;
  if (timer > 6000) {
    z = setInterval(() => {
      setTimerToNewValue();
    }, 1000);
  }

  return () => clearInterval(z);
}, [timer]);

Demo Here

about 4 years ago · Juan Pablo Isaza Denunciar

0

if you have to use timer you can use this code

export default function Timer() {
    const [timer, setTimer] = useState(10000);
 
    useEffect(() => {
        console.log(timer)
        const interval = setInterval(() => {
            if (timer>6000)
            setTimer(timer => timer - 1000);
        }, 1000);
        return () => clearInterval(interval);
    })
}
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