Stop execution of a sequence of events using $timeout

十年热恋 提交于 2019-12-24 17:53:10

问题


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.


回答1:


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);
    });
  };


来源:https://stackoverflow.com/questions/31056940/stop-execution-of-a-sequence-of-events-using-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!