I made a timer hook for react native which counts from from props to to props. It returns the current value of timer in seconds, start function, stop function, restart function and pause function in an object. Here is the timer code:
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
}
}
Everything works perfectly but when i try to render (or even console.log) the timer value, it counts faster than what should be. For example the timer will pass 20 seconds for every 15 seconds in real time. I am using Expo Go app for development and my device is an android phone. Am i doing something wrong? Here is how i use timer:
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>
)
}
For anyone who might be wondering what's wrong, the problem is with expo's development mode. I don't know why but it seems timing is faster in expo's development mode. Just toggle the development mode to production mode and time will become normal
I used this approach to create a timer before:
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>
}