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

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

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 Relatório

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 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