KingKongFrog
KingKongFrog

Reputation: 14429

Cleanest way to repeat ajax call in angular in a serial fashion and be able to cancel when needed?

I'm trying to repeat an ajax call for pulsing but using interval sometimes I have several ajax calls in queue because of network issues. How do I run an ajax call but only run the next one if they first one has come back successfull. In addition, I'd like to cancel the call if needed. Using interval this is easy as I use the clearInterval.

$scope.intervalLoop = $interval(function() {
  if ($scope.weAreClear)
    $scope.initSoftwareUpdate();
}, 5000);

Upvotes: 0

Views: 45

Answers (1)

Simon Z.
Simon Z.

Reputation: 497

As already indicated you can use a recursive function returning a $timeout:

  $scope.cancelled = false;

  $scope.recTimeoutFunction = function($scope) {
    return $timeout(function($scope) {
      //only start new pulse if user hasn't cancelled
      if(!$scope.cancelled)
      {
        $http(/* pulsing ajax call */)
          .then(function(res) {
            //after successful ajax call, start new timeout:
            $scope.recTimeoutFunction($scope);
          })
      }
    }, 5000, true, $scope);
  };

  //initially call the timeout function:
  $scope.recTimeoutFunction($scope);

  //function for the user to cancel pulsing messages
  $scope.cancel = function() {
    $scope.cancelled = true;
  }

Upvotes: 2

Related Questions