Stop angular $timeout timer after hitting back button

372 views Asked by At

In my Angular app, I have Page 1, and Page 2.

Page 1 is basically the home page with a button linking to Page 2.

Page 1 has an angular app called Page1App and a controller called Page1Ctrl. Page 2 has an angular app called Page2App and a controller called Page2Ctrl.

Page1App has Page2App as a dependency.

angular.module('Page1App', ['Page2App']);

In Page 2, there is a timer, that works like the timer in this JSFiddle (code duplicated below)

 $scope.nextPic = function() {
      $timeout.cancel(picTimeout)
      if (++$scope.picIndex >= $scope.pics.length) $scope.picIndex=0
      picTimeout = $timeout($scope.nextPic, 2000)
  }

  $scope.prevPic = function() {
      $timeout.cancel(picTimeout)
      if (--$scope.picIndex < 0 ) $scope.picIndex=$scope.pics.length-1
      picTimeout = $timeout($scope.nextPic, 2000)
  }
  picTimeout = $timeout($scope.nextPic, 2000)

The problem is, when I go back to Page 1 from Page 2, the timer continues running in the background, and occasionally makes an alert pop up - which is OK if you are on Page 2, but not OK if you already left Page 2.

How do I make everything from Page 2 stop when the user leaves it?

1

There are 1 answers

4
Kalhan.Toress On BEST ANSWER

You can listen for scope destroy event listener and clear the timeout.

for Ex:

$scope.$on('$destroy', function() {
    $timeout.cancel(picTimeout);
});

check the DOC for $destroy event of scopes.