[英]SetInterval can't be stopped by clearInterval when using useEffect
我尝试实现一个 function ,当 isPlaying 变量为真时开始倒计时,当它为假时停止,一般来说,它不起作用,它所做的只是同时启动多个间隔,当 isPlaying 改变时视频停止或重新开始播放
let interval useEffect(() => { if (isPlaying) { interval = setInterval(() => { setTimePassed((time) => time + 1) }, 1000); } else { console.log('clear interval'); clearInterval(interval); } return () => clearInterval(interval); }, [isPlaying])
您需要将间隔存储在 useRef 挂钩中,因为组件重新渲染您的间隔值设置为未定义,因为它不保留 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])
这对我有用,我只是将间隔放在 function 的边界之外,并在清除间隔时引用 _id。
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]) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.