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

144
Views
La función React Native useState setInterval no funciona correctamente

Estoy tratando de mostrar el temporizador de cuenta regresiva que comienza en 10 y disminuye hasta 0 cada segundo usando setState y setInterval para RN.

Mi vista se está actualizando, pero el temporizador no funciona correctamente. Va bastante rápido y salta entre 9 y 0 al azar. No se muestran errores dentro de mi código.

 import { StyleSheet, Text } from 'react-native' import React, {useState} from 'react' export default function Timer() { // Countdown timer logic upon click event const [time, setTime] = useState(10) setInterval(() => { setTime(time => time > 0 ? time - 1 : time = 10) },1000) return ( <Text style={styles.timer}>{time}</Text> ) } const styles = StyleSheet.create({ timer: { fontWeight: '700', fontSize: 24, color: '#00C261', fontFamily: 'Roboto', width: 30, textAlign: 'center', alignItems: 'center', justifyContent: 'center' } })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En cuanto a ahora, está llamando al intervalo en cada renderizado (compruebe iniciando sesión en el intervalo), después de algunos renderizados hay una "carrera de renderizado", en su lugar, intente poner la lógica en un enlace dedicado para que el intervalo solo se llame una vez.

Observe también que la expresión time = 10 devuelve 10 , por lo que su código funciona por error, debe tratar el estado como inmutable.

 export default function Timer() { const [time, setTime] = useState(10); useEffect(() => { const intervalID = setInterval(() => { setTime((time) => (time > 0 ? time - 1 : 10)); }, 1000); return () => { clearInterval(intervalID); }; }, []); return <Text style={styles.timer}>{time}</Text>; }
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!