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

114
Visualizações
My counter stop when i switch tab (reactjs)

I am new to javascript, and I made a counter. It works, however when the tab is inactive it stops and then resumes when I return to the page. Here is my code:

import React, { useEffect, useState } from 'react'

function TimeTracker(props){

    const [time, setTime] = useState(0);
    const [timerOn, setTimerOn] = useState(false);

useEffect(()=>{

        let interval = null;

        if(timerOn){
            interval = setInterval(()=>{
                setTime(prevTime => prevTime +10)
            }, 10)

        }else{
            clearInterval(interval)

        }

        return ()=> clearInterval(interval)

    },[timerOn])
    
    return(
    <div>
    
     <p>{("0" + Math.floor((time / 60000) % 60)).slice(-2)} mn</p>
     <p>{("0" + Math.floor((time / 1000) % 60)).slice(-2)} s</p>
     <button onClick={()=>setTimerOn(true)}>Start</button>
     <button onClick={()=>setTimerOn(false)}>Stop</button>


    
    </div>
    
    
    )
}

Thank you in advance for any help you can give me.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.

Thus, when you not focus on your tab, interval will not work. Its not React problem.

Check this question, I wish it help you.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your counter was not efficient

If you add a console.log before setTime and start the counter you will notice the extra renders

The code below will solve your issue:

import React, { useEffect, useState } from 'react'

function TimeTracker(props){

const [time, setTime] = useState(0);
const [timerOn, setTimerOn] = useState(false);

useEffect(()=>{

  let interval = null;
  if(timerOn){
      interval = setInterval(()=>{
          setTime(prevTime => prevTime +1)
      }, 1000)

  }else{
      clearInterval(interval)

  }

  return ()=> clearInterval(interval)

},[timerOn])

return(
<div>

 <p>0{Math.floor(time / 60)} mn</p>
 <p>{Math.floor(time % 60)} s</p>
 <button onClick={()=>setTimerOn(true)}>Start</button>
 <button onClick={()=>setTimerOn(false)}>Stop</button>



</div>


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