Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!