问题
I have some code that uses an AngularJS $timeout to call another function several times at specific intervals, using a loop. I'm trying to create a cancel function that will stop all the $timeouts from being processed. I realize I could probably do this with another loop, going through each $timeout, but sometimes the page will need to create thousands of $timeouts and so I was really hoping there would be some kind of way to stop all the currently pending $timeouts. The documentation here https://docs.angularjs.org/api/ng/service/$timeout seems to only really talk about using cancel() to stop a specific promise.
Is it possible to cancel all currently pending $timeouts at once in AngularJS and if so, how?
Here's a snippet of the code in question:
for(var i=1; i<=$scope.catalog.pages; i++) {
$scope.catalog.timeouts['fetch'+i] = $timeout(function() {
count++;
if (!$scope.catalog.isCancelled) {
$scope.results($scope.catalog.dataFile, {currentPage: count});
} else {
//cancel all the remaining timeouts somehow
}
}, 10*i);
}
回答1:
Angular timeouts works with promises, you could call the cancel method of that. $timeout.cancel
$scope.catalog.timeouts.forEach(function(promises) {
promises.cancel && promises.cancel();
});
来源:https://stackoverflow.com/questions/32314833/how-can-i-cancel-all-pending-timeouts