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

350
Vistas
¿Cómo puedo hacer que useEffect funcione dentro de mi función?

Actualmente, estoy tratando de construir un temporizador, pero se detiene después de un segundo. Estoy tratando de usar ganchos en React y estoy tratando de descubrir cómo implementar useEffect en mi función startTimer para que pueda realizar una cuenta regresiva.

 function InputTimer() { const [timerOn, setTimerOn] = useState(false); const [timerStart, setTimerStart] = useState(0); const [timerTime, setTimerTime] = useState(0); let timer; const startTimer = () => { setTimerOn(true); setTimerStart(0); setTimerTime(0); timer = setInterval(() => { const newTime = timerTime - 1; if (newTime >= 0) { setTimerTime(newTime); } else { clearInterval(timer); setTimerOn(false); alert("Countdown Ended"); } }, 1000); } }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Parece que su código está funcionando.

Sin embargo, simplemente establece el tiempo en cero, por lo que después de un segundo, sale.

Para probar correctamente su código, establezca el tiempo de inicio en 10 segundos: setTimerTime(10);

Código completo

 function InputTimer() { const [timerOn, setTimerOn] = useState(false); const [timerStart, setTimerStart] = useState(0); const [timerTime, setTimerTime] = useState(0); let timer; const startTimer = () => { setTimerOn(true); setTimerStart(10); // Change this line setTimerTime(0); timer = setInterval(() => { const newTime = timerTime - 1; if (newTime >= 0) { setTimerTime(newTime); } else { clearInterval(timer); setTimerOn(false); alert("Countdown Ended"); } }, 1000); } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Cerró el valor de timerTime en el ámbito de devolución de llamada de intervalo, nunca cambia.

Aquí hay un ejemplo mínimo de su lógica que se ejecuta:

Divida la lógica, use la devolución de llamada de intervalo para disminuir el tiempo y use un useEffect para verificar la condición de terminación. Use un React ref para almacenar la referencia del temporizador.

 function InputTimer() { const [timerTime, setTimerTime] = useState(10); const timerRef = useRef(); useEffect(() => { return () => clearInterval(timerRef.current); }, []); useEffect(() => { if (timerTime <= 0) { clearInterval(timerRef.current); alert("Countdown Ended"); } }, [timerTime]); const startTimer = () => { setTimerTime(10); timerRef.current = setInterval(() => { setTimerTime(time => time - 1); }, 1000); } return ( <> <div>Time: {timerTime}</div> <button type="button" onClick={startTimer}>Start</button> </> ) }

Editar cómo-puedo-obtener-uso-efecto-para-trabajar-dentro-de-mi-función

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