I was using a Boolean var for indication of loading so my code looked like this: (this example is in angularjs but i think it can be relevant for any ajax call handlers)
//HTML:
<div ng-show="$scope.isLoading">...LOADING...</div>
//JS:
//Init
$scope.isLoading = false;
//Executing http request:
$scope.isLoading = true;
mainService.post(alteredItems).then(function (response) {
init();
}).catch(function (err) {
$scope.callBack(err);
}).finally(function () {
$scope.isLoading = false;
});
function init() {
$scope.isLoading = true; //another loading
mainService.get().then(function (response) {
if (response) {
}
$scope.isLoading = false;
});
}
The problem I had was that if 1 ajax method will complete before the other one so the "isLoading" will be false, and the loader will not be displayed although the request has not yet ended.
I converted the $scope.isLoading to int. So now code looks like this:
//Init
$scope.isLoading = 0;
//Start any ajax call
$scope.isLoading++;
//Finish
$scope.isLoading--;
Which works great, also no need to change the html because of the casting. I can't find a drawback in this approach and it seems better than the Boolean option.
What do you think?
0
, then it's OK to use counters. \$\endgroup\$