Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

407
Views
ClearInterval no puede detener SetInterval cuando se usa useEffect

Intenté implementar una función que inicia una cuenta regresiva cuando la variable isPlaying es verdadera y se detiene cuando es falsa, en general, no funciona y todo lo que hace es iniciar varios intervalos simultáneamente, isPlaying cambia cuando el el video se detiene o comienza a reproducirse nuevamente

 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 answers
Answer question

0

necesita almacenar su intervalo en el gancho useRef como componente volver a renderizar su valor de intervalo está configurado como indefinido ya que no retiene el estado

 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 Report

0

Esto es lo que funcionó para mí, simplemente puse el intervalo fuera de los límites de la función y me referí al _id cuando despejé el intervalo.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!