How can I cancel all pending $timeouts?

为君一笑 提交于 2019-12-11 10:58:51

问题


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

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