我在做一个间隔的时候内存泄露了。我尝试了不同的方法来解决这个问题,但我找不到问题所在。
我的代码:
updated--
$scope.autoUpdatePageResult = function(group){
$scope.isAutoUpdate = !$scope.isAutoUpdate;
storageService.setLocalItem($scope.user + '-auto-update-results', $scope.isAutoUpdate);
if($scope.isAutoUpdate){
$scope.startInterval(group);
}
else {
$scope.stopInterval(group);
}
};
--updated
$scope.startInterval = function(group){
$scope.updateInterval = $interval(function() {
$scope.shouldReloadPage = false;
$scope.loading = true;
$scope.update = true;
$scope.allSessions = [];
for (var a in $scope.sessions){
$scope.allSessions[a] = $scope.sessions[a].started;
}
delete $scope.sessions;
$scope.sessionGroup = group.name;
$scope.getSessions();
}, 3*1000);
// 3 sec
};
$scope.$on('$destroy', function() {
storageService.setLocalItem($scope.user + '-auto-update-results', false);
});
$scope.stopInterval = function() {
$scope.loading = false;
$scope.shouldReloadPage = true;
if (angular.isDefined($scope.updateInterval)) {
$interval.cancel($scope.updateInterval);
$scope.updateInterval = undefined;
}
};这是在触发和记录updateInterval时(30秒)中图形的外观:

更新(不工作):
$scope.startInterval = function(group){
$scope.totalIntervals = [];
$scope.updateInterval = $interval(function() {
if($scope.totalIntervals.length > 1){
$interval.cancel($scope.totalIntervals[1]);
}
$scope.shouldReloadPage = false;
$scope.loading = true;
$scope.update = true;
$scope.allSessions = [];
for (var a in $scope.sessions){
$scope.allSessions[a] = $scope.sessions[a].started;
}
delete $scope.sessions;
$scope.sessionGroup = group.name;
$scope.getSessions();
$scope.totalIntervals.push($scope.updateInterval);
}, 3*1000);
};`发布于 2016-01-13 18:45:13
您只保留一次对上次启动间隔的引用。
一旦您停止间隔,如果自上次停止一个间隔以来启动了多个间隔,则只会删除最后一个运行间隔-而其他间隔将继续运行,而您没有引用它们。
如果您一次只需要一个间隔,则只需在创建新的$interval之前检查您的$scope.updateInterval即可。如果定义了它,则可以在创建新的引用并覆盖对旧引用的引用之前将其删除。
如果您需要同时运行多个间隔,您可以保留一个$interval引用数组,然后遍历整个数组来停止它们(使用push向数组添加一个间隔,并在关闭一个间隔时使用pop停止它)。+或者你可以通过$interval做一个循环,因为它将遍历所有的间隔引用,然后取消每个引用。
https://stackoverflow.com/questions/34763878
复制相似问题