最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJs stop $interval for specific controller - Stack Overflow

programmeradmin5浏览0评论

I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function.

I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function.

Share Improve this question edited Oct 24, 2016 at 8:59 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked Feb 4, 2016 at 8:36 jana91jana91 1313 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

You could use the cancel method to clean $interval object. You should cancel out the interval while leaving the controller.

For that you need to add eventListener over $scope's $destroy event, you could do cleaning stuff (eg. canceling interval object, canceling timeout object).

Code

var myInterval = $interval(function(){
   //your interval code
}, 1000)

//register this listener inside your controller where the interval belongs.
$scope.$on('$destroy', function(){
    $interval.cancel(myInterval)
});

Sample Plunkr

Add the interval variable in rootScope. And cancel it in the second controller whenever it gets opened as shown below.

First Controller

$rootScope.stopInterval = $interval(function(){
   //code goes here
}, 1000);

Second Controller

$interval.cancel($rootScope.stopInterval);

Note: Only flaw in this case is you need to stop it in all the controllers you use after first controller, but a reliable one.

发布评论

评论列表(0)

  1. 暂无评论