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

176
Visualizações
Keep checking connection if available in Node and clear setTimeout

In node i keep checking if connection is available if it is it will get token and store in variable but if not then catch error will be thrown and it will then execute setTimeout to try again in 2 seconds.

But i think i need a clean way to clear the setTimeout because when i log it i keep getting higher number in Symbol(asyncId) this to me feels like it keeps adding setTimeout more and more to memory?

export const getToken = async () => {
  try {
    if (!GLOBAL_VARS.authToken) {
      await auth(`Getting token`)
    }

    // Do more stuff
  } catch (error: any) {
    tokenTimeout()
  }
}

getToken()
export const tokenTimeout = () => {
  setTimeout(() => {
    getToken()
  }, 2000)
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Yest it will add more setTimeouts to the memory.

you can clear it like this:

export const tokenTimeout = setTimeout(() => {
    getToken()
  }, 2000)


export const getToken = async () => {
  try {
    if (!GLOBAL_VARS.authToken) {
      await auth(`Getting token`)
    }

    // Do more stuff
  } catch (error: any) {
    const timeout = tokenTimeout()
  }
}

getToken()

/// use it wherever you want 
clearTimeout(timeout);
about 4 years ago · Juan Pablo Isaza Relatório

0

Memory is going to increase because of whatever you are doing with auth() and not because you are creating timeouts.

The issue I see with your code is not really using async await properly. It should look more like

const sleep = (ms) => 
  new Promise((resolve) => {
    setTimeout(resolve, ms);
  });

export const getToken = async (count = 0) => {
  try {
    if (!GLOBAL_VARS.authToken) {
      await auth(`Getting token`);
    }
  } catch (error: any) {
    await sleep(2000);
    if (count < 10) await getToken(++count);
    else throw new Error('Taking too long to get auth token');
  }
}

(async function () {
  await getToken();
})();
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