angularMe angularMe - 4 months ago 37
Javascript Question

Terminate $interval on view leave

I have a simply counter running

doRefresh()
in an ionic/angular application, as you can see it is calling itself with the $interval, but when a user leaves this view. The counter is still running. I cant get it to stop running. I have tried many things including the code below. Please help. Thnk you

$interval(function () {
$scope.doRefresh();
console.log("refresh done");
}, 3000);

$scope.$on('$ionicView.enter', function(){

$scope.$on("$destroy",function(){
if (angular.isDefined($scope.doRefresh())) {
$interval.cancel($scope.doRefresh())
console.log("Destroyed");
}
});


});

Answer

$interval returns the promise you need to cancel the interval. See the following code:

var refresher = $interval(function () { 
  $scope.doRefresh(); 
  console.log("refresh done");
}, 3000);

$scope.$on('$ionicView.enter', function(){

$scope.$on("$destroy",function(){
    //This really wouldn't be needed, as refresher should always be defined.
    if (angular.isDefined(refresher)) {
        $interval.cancel(refresher);
        refresher = undefined;
        console.log("Destroyed");
    }
  });


});