Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

404
Visualizações
SetInterval can't be stopped by clearInterval when using useEffect

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])

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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])
about 4 years ago · Juan Pablo Isaza Relatório

0

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])
    }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda