Hice un gancho de temporizador para reaccionar nativo que cuenta from accesorios to accesorios. Devuelve el valor actual del temporizador en segundos, función de start , función de stop , función de restart y función de pause en un objeto. Aquí está el código del temporizador:
import { useState, useEffect, useRef } from 'react' export default function useTimer({ from, to, intervalS, finished }) { const [timer, setTimer] = useState(from) const interval = useRef() const start = () => { if (!interval.current) { interval.current = setInterval(() => { setTimer(timer => timer - intervalS) }, intervalS * 1000) } } const pause = () => { clearInterval(interval.current) interval.current = null } const stop = () => { clearInterval(interval.current) interval.current = null setTimer(from) } const restart = () => { clearInterval(interval.current) interval.current = null setTimer(from) start() } useEffect(() => { return () => { clearInterval(interval.current) } }, []) useEffect(() => { if (timer === to) { finished() clearInterval(interval.current) } }, [timer]) return { value: timer, start, pause, restart, stop } } Todo funciona perfectamente, pero cuando intento renderizar (o incluso console.log ) el valor del temporizador, cuenta más rápido de lo que debería ser. Por ejemplo, el temporizador pasará 20 segundos por cada 15 segundos en tiempo real. Estoy usando la aplicación Expo Go para el desarrollo y mi dispositivo es un teléfono Android. ¿Estoy haciendo algo mal? Así es como uso el temporizador:
export default function Countdown() { const [finished, setFinished] = useState(false) const timer = useTimer({ from: 60, to: 0, intervalS: 1, finished: () => setFinished(true) }) return ( <View style={{ alignItems: 'center' }}> <Typography variant="heading">{timer.value}</Typography> <Button title="start" onPress={timer.start} /> <Button title="pause" onPress={timer.pause} /> <Button title="restart" onPress={timer.restart} /> <Button title="stop" onPress={timer.stop} /> </View> ) }Para cualquiera que se esté preguntando qué está mal, el problema está en el modo de desarrollo de la exposición. No sé por qué, pero parece que el tiempo es más rápido en el modo de desarrollo de la exposición. Simplemente cambie el modo de desarrollo al modo de producción y el tiempo se normalizará.
Usé este enfoque para crear un temporizador antes:
const [intervalID, setIntervalID] = useState<any>(null) //Initially set to 60 secs const [testTime, setTestTime] = React.useState(60) useEffect(() => { setIntervalID(setInterval(() => { updateTimer(); }, 1000)); return () => clearInterval(intervalID); }, []) useEffect(() => { if (testTime <= 0) { //Timer hit zero return () => clearInterval(intervalID) } }, [testTime]) const updateTimer = () => { setTestTime(testTime => testTime - 1) } function displayTime(seconds) { const format = val => `0${Math.floor(val)}`.slice(-2) const minutes = (seconds % 3600) / 60 return [minutes, seconds % 60].map(format).join(':') } const getRemainingTime = () => { let finalTime = displayTime(testTime) return <Text style={{ alignSelf: 'center' }}>{finalTime} minutes left</Text> }