I have a countdown timer that I need to reset from more than one place in my React Native application. I have a service function that returns my updated time string and a variable that the setInterval
function is saved to via callbacks returnCountDown
and returnSetInterval
:
export const getCountdown = (callLength, returnCountDown, returnSetInterval) => {
let callLengthInMs = Date.parse('1970-01-01T00:' + callLength + 'Z')
const interval = setInterval(() => parseTimeString(), 1000, returnCountDown)
const parseTimeString = () => {
callLengthInMs -= 1000;
const timeLeft = new Date(callLengthInMs).toISOString().slice(14, -5)
returnCountDown(timeLeft);
}
returnSetInterval(interval);
}
Then in my function component I save the returned setInterval
function to state and call it under a certain condition, but clearInterval
does not work:
const CountDown = () => {
const [time, setTime] = useState(null);
const [callInterval, setCallInterval] = useState(null);
const callLength = useSelector(state => state.videosession.callLength);
useEffect(() => {
getCountdown(callLength, returnCountDown, returnSetInterval);
}, []);
const returnCountDown = timeLeft => {
setTime(timeLeft);
}
const returnSetInterval = interval => {
setCallInterval(interval)
}
time === '00:05'&& console.log('00:05 HIT') && clearInterval(callInterval); // does not work.
How can I achieve being able to call clearInterval
via an exported module if this is not the correct approach?
Many thanks in advance! :)
Update
When I console.log(typeof interval)
I get number
. This is the variable that is assigned to setInterval