I have been trying to create a timer that will log my clients out when they have been idol for over 10 minutes. I have created the code below which works fine as long as the user does not open a second tab. I have many clients that open a second window or tab and while the second tab is open the counter speeds up. I am looking for a way to improve the following code so that the tabs/windows can be in better sync.
var cookies='off'; // var to check if cookies are turned off
var alertTimes=0; // alturnative to cookies
$(function(){
resetCookies();
var loginTime=getCookie("loginTime");
if (loginTime!=null && loginTime!=""){ cookies='on'; }
checkAlerts();
});
function resetCookies(){
setCookie("loginTime",'10',1);
alertTimes=0;
}
function checkTime() {
if(cookies=='on'){
var loginTime=getCookie("loginTime");
if (loginTime!=null && loginTime!=""){
var newTime=loginTime-1;
if(newTime==0){ autoLogout(); return false;}
setCookie("loginTime",newTime,1);
}else{ autoLogout(); return false;}
}else{
alertTimes++;
if(alertTimes>=10){ autoLogout(); return false;}
}
setTimeout(checkTime, 600000);
}
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++){
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){ return unescape(y); }
}
}
function autoLogout(){
window.location.href=("logout.php");
}
Maybe this example will satisfy your needs?
also keep in mind that in this example server application is deciding if user session has expired