问题
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