[英]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.