Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 277a5ea

Browse files
joshkurzpetebacondarwin
authored andcommitted
docs($interval): remind the developer to destroy their intervals
It is essential that users of `$interval` destroy the interval when they are finished. Otherwise you can get memory leaks. Often `$intervals` are used in directives or controllers and developers don't think about what happens when the component is destroyed. If a directive/controller scope is destroyed, then the $interval should be destroyed as well. This could cause some issues with developers who assume that the interval will be cleared for them when the scope is destroyed. Closes #5377 I believe that the library could/should handle this as well, but thats another issue.
1 parent 9865a7c commit 277a5ea

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/ng/interval.js

+18-3
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ function $IntervalProvider() {
2424
* In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
2525
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
2626
* time.
27+
*
28+
* <div class="alert alert-warning">
29+
* **Note**: Intervals created by this service must be explicitly destroyed when you are finished
30+
* with them. In particular they are not automatically destroyed when a controller's scope or a
31+
* directive's element are destroyed.
32+
* You should take this into consideration and make sure to always cancel the interval at the
33+
* appropriate moment. See the example below for more details on how and when to do this.
34+
* </div>
2735
*
2836
* @param {function()} fn A function that should be called repeatedly.
2937
* @param {number} delay Number of milliseconds between each function call.
@@ -52,20 +60,27 @@ function $IntervalProvider() {
5260
$scope.blood_1 = $scope.blood_1 - 3;
5361
$scope.blood_2 = $scope.blood_2 - 4;
5462
} else {
55-
$interval.cancel(stop);
63+
$scope.stopFight();
5664
}
5765
}, 100);
5866
};
5967
6068
$scope.stopFight = function() {
61-
$interval.cancel(stop);
62-
stop = undefined;
69+
if (angular.isDefined(stop)) {
70+
$interval.cancel(stop);
71+
stop = undefined;
72+
}
6373
};
6474
6575
$scope.resetFight = function() {
6676
$scope.blood_1 = 100;
6777
$scope.blood_2 = 120;
6878
}
79+
80+
$scope.$on('$destroy', function() {
81+
// Make sure that the interval is destroyed too
82+
$scope.stopFight();
83+
});
6984
}
7085
7186
angular.module('time', [])

0 commit comments

Comments
 (0)