Stop time interval during navigation in angularjs

Viewed 13838

Currently i am using angular js

I have one get method to get data from server side in default.html page

function bindActiveLoans() {
            $http.get(rootUrlSingleEscaped + '/cooperativa/allunfundedloans/?authId=' + userInfo.UserId)
                 .success(function (response) {
                     if (response.Loans.length == 0) {
                         $scope.IsValues = false;
                         $scope.$apply();
                         return true;
                     }
                     $scope.IsValues = true;
                     $scope.unfundedLoans = response;
                 });
        };

        setInterval(function () {
            $scope.$apply(bindActiveLoans());
        }, 5000);

The above function helps to get the data from server side method in every 5 seconds.

Here, I have an issue.

Additionally I have some more pages, like

  • default2.html,default3.html,default4.html,default5.html.

    The timer is still running while i navigation default.html page to default1.html page. I want to only that timer running in default.html page.If i go to another page,then the timer should stop. How can we achieve it?

3 Answers

You can listen to the $routeChangeStart event and do the clearing of the interval depending on the route parameters,

  $scope.$on('$routeChangeStart', function (scope, next, current) {
           if(<next is not default.aspx>){
           // clear interval here
            }
  });

call clearInterval function when navigating from default page

e.g.

var myVar = setInterval(function () {
        $scope.$apply(bindActiveLoans());
    }, 5000);


function myStopFunction()
{
clearInterval(myVar);
} 

Call myStopFunction

Related