To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received:
function myFunction() {
var i=0;
var _onSuccess = function(response) {
if (response.status=== 'READY' || i >= 12) {
clearInterval(x);
if(response.status !== 'READY') {
$location.path('/errorView');
}
}
}
var x = setInterval(function () {
$rest.getSomething(_onSuccess)
}, 3000);
}
In addition to myFunction, there is another function that calls myFunction with a timeout. If the expected result is not received within 32 seconds, an error view is displayed.
function myFunction2() {
myFunction();
$timeout(function () {
$location.path('/routeWhenStatusReady');
}, 32000);
}
Is there a way to optimize this process? I would like myFunction2 to finish its timeout after 16 seconds if the Ready status is confirmed instead of waiting for the full 32 seconds...
Thank you!