Stop time interval during navigation in angularjs

Ramesh Rajendran picture Ramesh Rajendran · Dec 5, 2013 · Viewed 13.7k times · Source

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?

Answer

nacholibre picture nacholibre · Aug 12, 2014

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);
    });
}]);