CESCO
CESCO

Reputation: 7768

Stop execution of a sequence of events using $timeout

I am using this solution to start the sequence. But now I want to stop on a ng-click. The click event if firing OK, I have confirmed on the console.log. I have tried

$timeout.cancel($scope.StartChange);

But with no success, classes are still changing.

Upvotes: 1

Views: 1738

Answers (1)

Ana F
Ana F

Reputation: 641

This works, but I have no idea if it's the best solution: http://plnkr.co/edit/xKBHdFhXy93NqtpVooXe?p=preview

  var savePromise = function(promiseObj) {
    //saves promise and returns it
    $scope.terminateEarly.push(promiseObj);
    return promiseObj;
  };

  $scope.startChange = function() {
    console.log('start');
    $scope.state = 'b';
    console.log($scope.state);
    return savePromise($timeout(angular.noop, 3 * 1000))
     .then(function() {
      $scope.state = 'c';
      console.log($scope.state);

      return savePromise($timeout(angular.noop, 6 * 1000))})
      .then(function() {
        $scope.state = 'd';
        console.log($scope.state);
        return savePromise($timeout(angular.noop, 12 * 1000))})
        .then(function() {
          $scope.state = 'e';
           console.log($scope.state);
    });
  };

  $scope.stopChange = function(tId) {
    console.log('stop');
    $scope.terminateEarly.forEach(function(t){
      $timeout.cancel(t);
    });
  };

Upvotes: 1

Related Questions