简体   繁体   中英

cancelling angularjs timeout after route change not working

I'm have a timer that polls a server for data every 10 seconds. However, everytime a user switches to another controller, the timer should get destroyed. For some reason it's not happening with my code below. The timer keeps polling the server regardless if I change controllers.

controller.js

$scope.init = function() {
    //timer and timer stoper
    $scope.counter= 0;
    var mytimeout = $timeout($scope.onTimeout, 10000);

    $scope.$on('$locationChangeStart', function() {
    $timeout.cancel(mytimeout);
    });

   };

 $scope.onTimeout = function() {
  //polling server function
    $scope.counter++;
    var mytimeout = $timeout($scope.onTimeout, 10000);

    var increase = 0;
    inboxServ.check_newusers().then(function(data) {
        if (data == "true") {
            $scope.retrieveusers(increase);
        }
    });

   };

It seems like you have a scope issue. You have $scope.init() which creates a timeout (held by mytimeout ) and also wires up logic to cancel it if you start to change location. However, the function executed ( onTimeout ) starts another timeout, but assigns it to a different locally scoped mytimeout .

I would expect it, as is, to cancel the first timeout if you change location within the first 10 seconds, and fail to do so any time after that because the variables are different.

It might be as simple as changing it to something like this:

$scope.init = function() {

     //timer and timer stoper
     $scope.counter= 0;
     $scope.mytimeout = $timeout($scope.onTimeout, 10000);

     $scope.$on('$locationChangeStart', function() {
         $timeout.cancel($scope.mytimeout);
     });
};

$scope.onTimeout = function() {
     //polling server function
     $scope.counter++;
     $scope.mytimeout = $timeout($scope.onTimeout, 10000);

     var increase = 0;
     inboxServ.check_newusers().then(function(data) {
         if (data == "true") {
             $scope.retrieveusers(increase);
         }
     });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM