Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
why cleanup function dos not work in react app

timer dos not stop after we go into another component and then loser component will runing but i can see unmounted in console. i mean want to cleanup timer function like componentWillUnmount in class components.

    function timeDown() {
        if (stepName == 'question') {
            let haveTime = state.haveTime;
            let time = setInterval(() => {
                haveTime -= 1;
                setState({ haveTime })
            }, 1000);
            setTimeout(() => {
                clearInterval(time)
                dispatch(getNameStep(states.step))
            }, 60000);
  } else {
    return
  }
}
useEffect(() => {
    timeDown()
    return () => {
      console.log('unmounted')
      timeDown()
    }
  }, [])
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

time is not a timeout but an interval:

clearTimeout(time) ⇨ clearInterval(time)

about 4 years ago · Juan Pablo Isaza Denunciar

0

There's two kinds of "timer" functions. setInterval() and setTimeout(). Note that each of these have their respective clear functions.

When you make a timer using setInterval(), you must clear it with clearInterval(), same for setTimeout() and clearTimeout().

time, in your example, is an interval. The following code should work:

function timeDown() {
  if (stepName == 'question') {
    let haveTime = state.haveTime;
    let time = setInterval(() => {
        haveTime -= 1;
        setState({ haveTime })
      }, 1000);
    setTimeout(() => {
        clearInterval(time)
        dispatch(getNameStep(states.step))
      }, 60000);
  } else {
    return
  }
}

useEffect(() => {
    timeDown()
    return () => {
      console.log('unmounted')
      timeDown()
    }
  }, [])
about 4 years ago · Juan Pablo Isaza Denunciar

0

https://medium.com/@monica1109/scheduling-settimeout-and-setinterval-ca2ee50cd99f#:~:text=The%20only%20difference%20is%20%2C,should%20call%20clearInterval(timerId)%20. This blog clearly explains the difference between settimeout & setInterval

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda