title: AngularJS: How to chain $timeout inside $watch
body: <p>I am trying to chain two $timeout methods inside $watch. $watch is used to see if user has performed any action. If yes, then I am cancelling both the $timeout instances. Here is the code snippet.</p>
  
  <pre><code>.run(['$rootScope',  '$location', '$timeout', 'applicationCache', function ($rootScope, $location, $timeout, applicationCache) {
  var popupTimer, logoutTimer;
  var logoutInterval = 10000, popupInterval = 5000;
  $rootScope.$watch(function detectIdle() {
      if($rootScope.userLoggedIn){
          (popupTimer) ? $timeout.cancel(popupTimer) : undefined; // check if timer running, cancel it
          (logoutTimer) ? $timeout.cancel(logoutTimer) : undefined; // check if other timer running, cancel it
          popupTimer = $timeout(function(){
                  console.log("show popup");
                  logoutTimer = $timeout(function(){
                      console.log("logout");
                      $rootScope.userLoggedIn = false; // set logged In status to false
                      applicationCache.removeAll(); // destroy all session storage
                      $location.path("/login");
                  },logoutInterval);
              },popupInterval);
      }
  });
  }])
  </code></pre>
  
  <p>What I want to achieve is in idle consition, show a popup after 5 second to user that his/her session is going to expire. If there is no interaction, he is logged out after 10 seconds. If he interacts cancel both the timer and re-initialize the popup timer. </p>
  
  <p>The problem I am facing is, if no interaction is performed at all, the inner timeout doesn't get executed. It gets cancelled as soon as it is initialized. In console "logout" is never printed. Only thing I am seeing in console is "show popup" getting printed repeatedly.</p>
  
  <p>I guess $watch is getting executed as soon as the second timer is initialized and thus cancelling the inside timer.</p>
  
  <p>What can be done to handle this issue?</p>