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

后端 未结 1 401
南旧
南旧 2021-01-21 19:21

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

相关标签:
1条回答
  • 2021-01-21 19:45

    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.

    0 讨论(0)
提交回复
热议问题