Home > Back-end >  Keep checking connection if available in Node and clear setTimeout
Keep checking connection if available in Node and clear setTimeout

Time:03-10

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

CodePudding user response:

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

CodePudding user response:

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();
})();
  • Related