I have a countdown timer set at every second. Every time I would reset the counter and choose another period to countdown, the previous timer keeps counting and will have multiple timers in the background. I tried to reset the timer.
How can I stop the timer each time I go back and choose another period.
Here is my code bellow:
useEffect(() => {
startTimer()
return () => {
if (intervalRef.current) clearInterval(intervalRef.current)
}
}, [intervalRef.current])
const clearTimer = () => {
setTimer([])
navigation.navigate('Home')
}
const startTimer = () => {
let { total, remainingDay, remainingHour, remainingMinute, remainingSecond } = calculateTimeLeft()
const id = setInterval(() => {
if (total > 0) {
setTimer([
(remainingDay < 10) ? "0" + remainingDay : remainingDay,
(remainingHour < 10) ? "0" + remainingHour : remainingHour,
(remainingMinute < 10) ? "0" + remainingMinute : remainingMinute,
(remainingSecond < 10) ? "0" + remainingSecond : remainingSecond])
calculateTimeLeft()
}
else {
setTimer([])
clearInterval(id)
setPlantType(false)
setItemType([])
phaseDay.current = []
}
handlerAirNotification()
}, 1000);
intervalRef.current = id
}
useEffect(() => {
startTimer()
return () => {
if (intervalRef.current) clearInterval(intervalRef.current)
}
}, [intervalRef.current])
const calculateTimeLeft = () => {
let sum = parseInt(phaseDay.current[0]) + parseInt(phaseDay.current[1]) + parseInt(phaseDay.current[2]) + parseInt(phaseDay.current[3])
const today = new Date();
const requiredDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + sum)
const total = requiredDate - Date.parse(new Date())
const seconds = 1000
const minute = seconds * 60
const hour = minute * 60
const days = hour * 24
const remainingDay = Math.floor(total / days)
const remainingHour = Math.floor((total / hour) % 24)
const remainingMinute = Math.floor((total / minute) % 60)
const remainingSecond = Math.floor((total / seconds) % 60)
dayLeft = remainingMinute
return { total, remainingDay, remainingHour, remainingMinute, remainingSecond };
}
const fetchData = () => {
DataService.getDays(itemType)
.then(response => {
response.data.map(data => {
setSeries(series => [...series, data.Days])
phaseDay.current = [...phaseDay.current, data.Days]
});
})
.catch(e => {
console.log(e);
});
}
What I have tried:
I tried to setTimer & phaseDays but it still not working