我想在网页中实现自动注销功能,当网页上没有活动时,它将显示登录页面预定的时间间隔(例如15分钟,30分钟,45分钟和60分钟)。 我编写了一个侦听特定事件并重置计数器的函数。如果计数器超过,那么我将调用登录页面。
这里的问题是,在用户事件上调用setInterval会进行如此多的函数调用。让我知道,如何避免这种情况。 或者,是否有任何其他解决方案来实现这一目标。
var inActiveTimeout = 5; //temp
var minInActiveTimeout = 5;
var idleTime = minInActiveTimeout;
var idleIntervalTimer;
function listenEvents() {
idleIntervalTimer = setInterval(logoutTimeCounter, minInActiveTimeout * 60000); // multiple of 1 minute
$('body').mousemove(function (e) {
console.log(new Date($.now()) + " :: " + "Mouse Move"+idleTime);
idleTime = minInActiveTimeout;
clearInterval(idleIntervalTimer);
idleIntervalTimer = setInterval(logoutTimeCounter, minInActiveTimeout * 60000);
});
$('body').keypress(function (e) {
console.log(new Date($.now()) + " :: " + "Key Press"+idleTime);
idleTime = minInActiveTimeout;
clearInterval(idleIntervalTimer);
idleIntervalTimer = setInterval(logoutTimeCounter, minInActiveTimeout * 60000);
});
$('body').click(function () {
console.log(new Date($.now()) + " :: " + "Body Click"+idleTime);
idleTime = minInActiveTimeout;
clearInterval(idleIntervalTimer);
idleIntervalTimer = setInterval(logoutTimeCounter, minInActiveTimeout * 60000);
});
}
function logoutTimeCounter() {
console.log(new Date($.now()) + " :: " + "idleTime >>" + idleTime + "inActiveTimeout >>" + inActiveTimeout);
if (idleTime === inActiveTimeout) {
console.log(" <<Warning >>");
$('#InactiveTimeoutModal').modal({backdrop: 'static', keyboard: false});
$("#InactiveTimeoutModal").modal("show");
clearInterval(idleIntervalTimer);
setTimeout(logoutTimeCounter, 60000);
}
else if (idleTime > inActiveTimeout) { // 20 minutes
console.log(new Date($.now()) + " :: " + "<< Time elapsed Hide and Logout>>");
$("#InactiveTimeoutModal").modal("hide");
}
idleTime = idleTime + minInActiveTimeout;
}
由于
答案 0 :(得分:2)
那应该执行Back-end。
如果不可能,,, 您必须将用户事件监视为滚动,鼠标移动,单击。
var previous = 0;
document.addEventListener("mousemove", function(evt) {
if(previous > 0) return;
previous++;
});
document.addEventListener("click", function(evt) {
if(previous > 0) return;
previous++;
});
window.addEventListener("scroll", function(evt) {
if(previous > 0) return;
previous++;
});
//other event check..
//document.addEventListener....
setInterval(function(){
if(previous > 0 )console.log("detect user action");
else console.log("not detect user action");
},10000);
答案 1 :(得分:0)
有一个很好的方法(但是您需要添加Jquery来绑定事件):
var stop = false;
var initial_timer = (1000*15);
var timer = initial_timer;
var logoutUrl = 'unlock.html?last_page_visited='+window.location.pathname ; // URL to logout page.
function logOut(){
window.location = logoutUrl;
}
if(!stop){
setInterval(function(){
timer-=1000;
console.log("Timer:"+timer);
if(timer==0 || timer<0){
logOut()
stop = true;
}
}, 1000);
}
$('body').bind('click dblclick mousedown mouseenter mouseleave keyup mouseover',
function(e){
timer = initial_timer;
});
有关更多详细信息或完整示例: https://github.com/Sanix-Darker/LogOutTimer
在这里查看: https://jsbin.com/dabobil/edit?html,js,console,output