Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop time interval during navigation in angularjs

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?

like image 436
Ramesh Rajendran Avatar asked Dec 05 '13 05:12

Ramesh Rajendran


2 Answers

From the angularjs example in the $interval API page.

    var interval = $interval(function() {
        console.log('say hello');
    }, 1000);

    $interval.cancel(interval);

With $interval.cancel(var) you can stop the interval and if you want to stop it when navigating to another page you should try something like this.

var interval = null;

module.controller('SomeController', '$interval', function($interval) {
    interval = $interval(function() {
        ...
    }, 2000);
}).run(['$rootScope', '$interval', function($rootScope, $interval) {
    $rootScope.$on('$routeChangeStart', function() {
        $interval.cancel(interval);
    });
}]);
like image 97
nacholibre Avatar answered Oct 12 '22 15:10

nacholibre


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
            }
  });
like image 35
Jayantha Lal Sirisena Avatar answered Oct 12 '22 16:10

Jayantha Lal Sirisena