Javascript AngularJS:如何在$watch中链接$timeout

Javascript AngularJS:如何在$watch中链接$timeout,javascript,angularjs,timeout,watch,Javascript,Angularjs,Timeout,Watch,我试图在$watch中链接两个$timeout方法$watch用于查看用户是否执行了任何操作。如果是,那么我将取消这两个$timeout实例。下面是代码片段 .run(['$rootScope', '$location', '$timeout', 'applicationCache', function ($rootScope, $location, $timeout, applicationCache) { var popupTimer, logoutTimer; var logoutInt

我试图在$watch中链接两个$timeout方法$watch用于查看用户是否执行了任何操作。如果是,那么我将取消这两个$timeout实例。下面是代码片段

.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);
    }
});
}])
我想实现的是在空闲状态下,在5秒钟后向用户显示一个弹出窗口,说明他/她的会话即将过期。如果没有交互,他将在10秒后注销。如果他进行交互,则取消计时器并重新初始化弹出计时器

我面临的问题是,如果根本不执行任何交互,那么内部超时就不会执行。一旦初始化,它就会被取消。在控制台中,永远不会打印“注销”。我在控制台中看到的唯一一件事是“显示弹出窗口”被反复打印

我猜$watch会在第二个计时器初始化后立即执行,从而取消内部计时器


如何处理这个问题?

我会使用一些布尔变量。请参见isInProgress:

.run(['$rootScope',  '$location', '$timeout', 'applicationCache', function ($rootScope, $location, $timeout, applicationCache) {
var popupTimer, logoutTimer, isInProgress= false;
var logoutInterval = 10000, popupInterval = 5000;
$rootScope.$watch(function detectIdle() {
    if($rootScope.userLoggedIn && !isInProgress){
        (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(){
                    isInProgress = false;
                    console.log("logout");
                    $rootScope.userLoggedIn = false; // set logged In status to false
                    applicationCache.removeAll(); // destroy all session storage
                    $location.path("/login");
                },logoutInterval);
            },popupInterval);
    }
    isInProgress = true;
});
}])

谢谢你的回复。但这种方法的问题是,一旦“isInProgress”设置为“false”,如果用户对弹出窗口执行某些操作,两个计时器都不会被取消。他仍将被注销。此外,设置“isInProgress=true”将使if条件永远失败。