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

121
Views
Botón de alternar usando una bandera Reaccionar

Cuando se presiona un botón, llama a la función toggleTimer() . Ahora, cuando presiono este botón, se detiene de inmediato ; sin embargo, cuando presiono el botón por segunda vez, no se reanuda de inmediato. El objetivo es hacer que el botón cambie entre estos 2 estados inmediatamente después de presionarlo.

Cuando ejecuto el programa, noto extrañamente que tengo que presionar mi botón muchas veces antes de que funcione el comportamiento de pausa. Creo que esto se debe a la variable global let paused=true , pero no estoy seguro de cómo resolver esto.

 ///////PAUSE TIMER///////////////// let paused = true; let holdValue; function toggleTimer(){ if (paused===true){ // if paused, we clear timer and save value paused = false; holdValue= remainingTime; clearInterval(timerRef.current); } else if (paused===false) { //if not paused, we can restart timer using our saved value paused = true; startTimer(); // call our function to start timer setRemainingTime(holdValue); // update the remaining time using our saved value } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Creo que tienes razón acerca de que la var global hace que el comportamiento sea extraño.

Entonces, la solución es usar un estado en su componente de botón:

 const [paused, setPaused] = useState(false)

Luego, debe combinarlo con un useEffect que manejará el temporizador (no estoy seguro de haberlo entendido correctamente, pero debería poder adaptarlo a sus necesidades):

 const Example = () => { const [paused, setPaused] = useState(false); useEffect(() => { let timer; if (!paused) { timer = setInterval(() => { // Do something }, 10000); } else { clearInterval(timer); } return () => clearInterval(timer); }, [paused]); return <Button onClick={() => setPaused(!paused)}>Button</Button>; };

Aquí, cuando la paused es falsa, el temporizador (intervalo) llamará a ejecutar su devolución de llamada (// Hacer algo) cada 10 segundos, luego, cuando haga clic en el botón pausado, cambiará a falso para que useEffect se ejecute y el tiempo borre el temporizador. Si desea volver a iniciarlo, haga clic en y el botón, que cambiará el estado de pausa y useEffect reiniciará el intervalo.

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!