0

I have a function with a an http request nested inside another as well as loops inside both the requests. I would show it but it's really long and messy and would only confuse things further. I've been trying to make this function run indefinitely but I have been unsuccessful so far

Heres what I tried so far:

while(true){
 myFunc();
}

in the above case function simply doesnt run

setInterval(myFunc, 1000);

function starts a new run every 1 second which makes it an absolute mess. The function itself takes around 30 mins to stop running which is 1800000 ms.

setInterval(myFunc, 1800000);

function never runs, didnt wait 30 mins to see if it would start running though

the only thing that "works" is calling it recursively inside an if statement in the function that checks if it's about to finish but this will cause memory leaks.

Any tips on what to do to get the function to run again after it finishes, ad infinitum?

2 Answers 2

2

In your first example the blocking execution of the while loop prevents any promises you've made from being able to settle. If myFunc returns a Promise or is async then you can await the function call.

Do note that since currently node doesn't support top-level await, you'll have to wrap your program in an async function in order to be able to await myFunc.

function myFunc(){
  return new Promise((res, rej)=>{
    setTimeout(()=>{
      console.log("Resolved")
      res()
    }, 1000)
  })
}

(async () => {
  while(true) await myFunc()
})()

This way might be preferable if you care about the return value of myFunc inside your while loop.

Another option is to simply use process.nextTick (or setImmediate or setTimeout with a delay of 0ms) at the end of your function to immediately reschedule another execution of myFunc. Doing it this way ensures that you won't reach the maximum call stack limit or "leak memory"

async function myFunc(){
  // sleep for 1 second
  await new Promise(res=>setTimeout(res,1000))
  console.log("Finished myFunc")
  process.nextTick(myFunc)
  // setImmediate(myFunc)
  // setTimeout(myFunc, 0)
}

myFunc() // initial call to myFunc

If you're still having problems, I would recommend taking a look into the code of myFunc itself and ensuring that all your promises eventually resolve and/or create a system that waits a maximum amount of time before cancelling.

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure if I get it. But did you try to wait until the function finishes?

while(true){
  await myFunc();
}

and myFunc is something like that:

// create your function
async function myFunc() {
   // implement your http request that returns a promise
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.