[英]AngularJS: How to chain $timeout inside $watch
我试图在$ 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;
});
}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.