Please check below it might be some helpful,
My requirements: Like every 5 secs need to call a service if we get back required data we need to stop calling the service and continue with next flow. Else call service again after 5 seconds.
Conditions to stop service invocation were like after max number of retries (in my case 20 times) or after certain time (in my case 120 seconds).
Note: I was using in typescript
let maxTimeToRetry = 120000; // in ms
let retryCount = 0;
let retryTimeout = 5000; // in ms
let maxRetries = 20;
const startTime = new Date().getTime();
// Need to use self inside of this, inside setInterval method;
const interval = setInterval(function () {
retryCount++; // INCREMENT RETRY COUNTER
self.service.getData(requestParams).subscribe(result => {
if (result.conditionTrue) {
clearInterval(interval); // to stop the timer or to stop further calling of service
//any execution after getting data
}
});
if ((new Date().getTime() - startTime > maxTimeToRetry) || (retryCount === maxRetries)) {
clearInterval(interval);
// any execution
}
}, retryTimeout);