I've tried to implement a function that starts a count down when the isPlaying variable is truthy and it stops when it's falsy, in general, it doesn't work and all it does is just start multiple intervals simultaneously, The isPlaying changes when the video stops or start playing again
let interval
useEffect(() => {
if (isPlaying) {
interval = setInterval(() => {
setTimePassed((time) => time + 1)
}, 1000);
} else {
console.log('clear interval');
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isPlaying])
you need to store your interval in the useRef hook as component rerender s your interval value is set to undefine as it does not retain the state
let interval = useRef();
useEffect(() => {
if (isPlaying) {
interval.current = setInterval(() => {
setTimePassed((time) => time + 1)
}, 1000);
} else {
console.log('clear interval');
clearInterval(interval.current);
}
return () => clearInterval(interval.current);
}, [isPlaying])
This is what worked for me, I just put the interval outside the boundaries of the function and referred to the _id when clear interval.
let interval = null
export default function PlayerBar() {
const [isReady, setIsReady] = useState(false)
const [isPlaying, setIsPlaying] = useRecoilState(store.playingState)
const [volume, setVolume] = useState(100)
const [duration, setDuration] = useState<number>()
const [timePassed, setTimePassed] = useState<number>(0)
// const [intervalStatus, setIntervalStatus] = useState<any>()
const player = useRef<any>()
const timePassedStatus = useMemo(() => duration - timePassed, [timePassed])
const durationStatus = useMemo(() => ('' + (duration / 60)).split('.').join(':'), [duration])
useEffect(() => {
if (isPlaying) {
interval = setInterval(() => {
setTimePassed((time) => time + 1)
}, 1000);
}else if(interval){
clearInterval(interval._id)
}
return () => {clearInterval(interval)};
}, [isPlaying])
}