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

三世轮回 提交于 2019-12-02 04:23:33
Renan Ferreira

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.

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