Reputation: 1723
Let's say I have this pseudo code:
var STATUS = '';
while (STATUS !== "SUCCEEDED") {
STATUS = getStatus();
anotherFunc();
delay(3s);
}
The goal of this code is to keep calling an api to check a status of something, the api returns IN_PROGRESS or SUCCEEDED. So I want the while loop to keep calling getStatus()
to get the value of STATUS and break the loop when it is SUCCEEDED. I also want to put a delay between each iteration.
This can't be done easily with Nodejs. So please help me out.
Upvotes: 1
Views: 3581
Reputation: 4778
you don't even need a while loop for that, simply use setInterval()
and within the callback check if your condition is satisfied to clear the created interval.
var STATUS = '',
idx = setInterval(function() {
STATUS = getStatus();
if (STATUS === "SUCCEEDED") { // I guess you wanted a check for STATUS instead of VAR
return clearInterval(idx);
}
anotherFunc();
}, 3000); // the interval when to call the function again 3000ms = 3sek
Upvotes: 2
Reputation: 383
You can use setInterval
to continually do something on a delay. It accepts a function which you can use to do the api call, but before you do the call you should check if the last call was successful.
Once a call is successful you can clear the interval.
https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args
Upvotes: 0