问题
Quick question about the $interval service in angular. Looking at the docs ($interval) they warn you to manually cancel intervals, but you have the option of providing a count parameter upon initialization. Once the timer has "ticked" past the allotted count does it cancel itself or simply stop calling the function and live on in the background?
回答1:
TL;DR; After the count, the interval is cleared.
As the same documentation says, it is recommended that you cancel the $interval when the scope of your controller is detroyed. Something like:
var t = $interval(function(){
...
}, 1000);
$scope.$on('$destroy', function(){
$interval.cancel(t);
});
The delay parameter is time interval which the function is called. In the example above, the function is called every 1000 milliseconds. If you don't cancel the $interval, Angular will hold a reference to it, and may continue to execute your function, causing strange behaviors in your app.
Considering that the $interval provider is just a wrapper of the native setInterval(), with the adition of the $apply, looking at the Angular implementation (https://github.com/angular/angular.js/blob/master/src/ng/interval.js), we can find this snippet of code:
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
So, the promise created by the provider is resolved, and the interval is cleared. The cancel method does this:
intervals[promise.$$intervalId].reject('canceled');
$window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
So, I think your assumption is right. After the count, the interval is already cleared.
来源:https://stackoverflow.com/questions/31363430/does-the-angular-interval-cancel-itself-after-exceeding-count-parameter