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

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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