Does the angular $interval cancel itself after exceeding 'count' parameter?

一世执手 提交于 2019-12-20 05:23:29

问题


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

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