Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
Mi contador se detiene cuando cambio de pestaña (reactjs)

Soy nuevo en javascript e hice un contador. Funciona, sin embargo, cuando la pestaña está inactiva, se detiene y luego se reanuda cuando regreso a la página. Aquí está mi código:

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

Desde ya agradezco cualquier ayuda que me puedan brindar.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En la mayoría de los navegadores, las pestañas inactivas tienen una ejecución de baja prioridad y esto puede afectar los temporizadores de JavaScript.

Por lo tanto, cuando no se concentre en su pestaña, el intervalo no funcionará. No es un problema de reacción.

Revisa esta pregunta, deseo que te ayude.

about 4 years ago · Juan Pablo Isaza Report

0

Su contador no fue eficiente

Si agrega un archivo console.log antes de setTime e inicia el contador, notará los renderizados adicionales

El siguiente código resolverá su problema:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!