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

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

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 Denunciar

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