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

149
Visualizações
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 Respostas
Responde à pergunta

0

time is not a timeout but an interval:

clearTimeout(time) ⇨ clearInterval(time)

about 4 years ago · Juan Pablo Isaza Relatório

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 Relatório

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