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

163
Visualizações
how to clear setTimeOut when component unmounts

i try to get Items data. if request response less than 1 i have to request again. so i write a recursive function with setTimeout. but when i try to change my route function keeps working. window.clearTimeout() or global.clearTimeOut() not worked here when component unmounts. Do i miss something?

  useEffect(() => {
   getItems(params);
   return () => {
     window.clearTimeout();
     global.clearTimeout();
   }
 }, []);



const getItems = async(params) => {
 try {
  const { data = []} = await axios.get('/some-endpoint',params);
  dispatch({ type: ITEMS_START });
  if (data.length === 0) {
    setTimeout(() => {
      getItems(params);
    }, 5000);
  } else {
    dispatch({ type: ITEMS_SUCCESS, payload: { data } });
  }
 } catch (error) {
  dispatch({ type: ITEMS_ERROR, payload: error });
 }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use a ref to store the timeout ID and then clear that timeout.

 const timeoutRef = React.useRef();

useEffect(() => {
   getItems(params);
   return () => {
     window.clearTimeout(timeoutRef.current);
   }
 }, []);



const getItems = async(params) => {
 try {
  const { data = []} = await axios.get('/some-endpoint',params);
  dispatch({ type: ITEMS_START });
  if (data.length === 0) {
    timeoutRef.current = setTimeout(() => {
      getItems(params);
    }, 5000);
  } else {
    dispatch({ type: ITEMS_SUCCESS, payload: { data } });
  }
 } catch (error) {
  dispatch({ type: ITEMS_ERROR, payload: error });
 }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Create a reference you can set your timeout too that the unmount can call back to.

let timeout = null;

useEffect(() => {
    getItems();
    return () => {
      if(timeout)
        clearTimeOut(timeout)
    }
})

const getItems = () => {
    timeout = setTimeOut(() => work, 5000);
}

This is the general idea.

about 4 years ago · Juan Pablo Isaza Relatório

0

Each SetTimeout ( and setInterval ) returns a number which can be used to clear it. ie, var x = setTimeout(() => console.log('timeout'),1000); clearTimeout(x); will do nothing.

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