Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite async loops using setInterval() [duplicate]

I have nodejs app that needs a few infinite loops which call async functions. I was considering implementing the following:

async function execute1() {
   ...do some async work...
}

async function execute2() {
   ...do some async work...
}

setInterval(execute1, 500)
setInterval(execute2, 500)

My concern is that if the async functions will take a long time to complete, the open references will pile up and this can result in a memory crash down the line.

  1. is setInterval the right tool for this job? is there a more suitable tool?
  2. What is the most elegant method to make sure the execute() function will not start if the previous run hasn't return?
like image 387
amit Avatar asked Feb 11 '19 16:02

amit


1 Answers

setInterval isn't the right tool because it's unaware of promises and can't maintain correct control flow.

It can be async function with infinite loop:

async function execute1() {
  while (true) {
    await new Promise(resolve => setTimeout(resolve, 500));
    // ...do some async work...  
  }
}

execute1();
like image 93
Estus Flask Avatar answered Sep 24 '22 23:09

Estus Flask