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

116
Views
El temporizador de cuenta regresiva que usa el componente funcional en ReactJS no funciona correctamente

Quiero hacer un temporizador de cuenta regresiva con botones de inicio, parada, reanudación y reinicio. Sin embargo, no pude entender por qué mi código no funciona. Supongo que el problema radica en la parte del temporizador, setInterval y clearInterval.

He adjuntado fragmentos de mi código a continuación.

La ayuda sería muy apreciada, gracias!

 function Countdown() { const [ timerRunning, setTimerRunning ] = useState(false); const [ startTime, setStartTime ] = useState(0); const [ totalTime, setTotalTime ] = useState(0); var timer; const startTimer = () => { setTimerRunning(true); setStartTime(totalTime); setTotalTime(totalTime); timer = setInterval(() => { const remainingTime = totalTime - 1000; if (remainingTime >= 0) { setTotalTime(remainingTime); } else { clearInterval(timer); setTimerRunning(false); setStartTime(0); setTotalTime(0); } }, 1000); }; const stopTimer = () => { clearInterval(timer); setTimerRunning(false); };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

tienes que poner tu setInterval en React.useEffect echa un vistazo a esta publicación algunas sugerencias para tu código:

  • use className en lugar del atributo de clase en sus elementos.
  • no use var ni deje reaccionar componentes funcionales.
about 4 years ago · Juan Pablo Isaza Report

0

useState no cambia el valor inmediatamente. Por lo que su valor en realidad no está cambiando. Para evitar esto, use el gancho UseEffect .

 useEffect(() => { let intervalid if (timerRunning){ intervalid = setInterval(() => { const remainingTime = totalTime - 1000; if (remainingTime >= 0) { setTotalTime(remainingTime); } else { clearInterval(intervalid); setTimerRunning(false); setStartTime(0); setTotalTime(0); } }, 1000); } return () => { clearInterval(intervalid) } }, [timerRunning,totalTime])
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!