我想在会话超时1分钟之前显示登录弹出窗口。最大会话空闲超时值为1800秒(30分钟)。所以我使用了一个计数器变量,如 idlecount 。使用setInterval()我正在增加该变量值。所以现在当变量值是1740(即我的空闲会话超时值1800-60秒)时,我将显示登录弹出窗口(具有2个按钮(1)让我保持登录状态(2)退出)。 问题是setInterval()无法正确维护变量 idlecount 的值。由于该登录弹出窗口无法正常工作。
答案 0 :(得分:0)
当您要依赖实际的到期时间时,不要使用超时或setinterval,因为它们不可靠。另外,请注意刷新将取消setTimeout / setInterval。 相反,您应该使用setInterval,每隔x秒检查一次会话是否过期,并根据当前的Date()对象对其进行检查。
示例:
setInterval(function(){
var decodedToken = localStorage.getItem('user_token');
if (decodedToken.exp < new Date().getTime()/1000) {
// Token is expired
}
}, 3000);
答案 1 :(得分:0)
我花了几个小时,希望能再感激一下..
const
DelayLimit = 1, // unit expressed in minutes, so, this is 1 minute.
DelayChecking = 3; // unit expressed in seconds, so, this is 3 seconds.
function f_Delay(ninutes2wait, seconds2Check, delayOut_fct, elapseTime_fct ) {
let c_Delay =
{
rf_DelayOut : delayOut_fct || function(){},
rf_ElapseTime : elapseTime_fct || function(){},
rf_delay : ninutes2wait *60*1000,
Date_Start : Date.now(),
Interval_ID : null
}
c_Delay.Interval_ID = setInterval(function (infos) {
let curDateDiff = Date.now() - infos.Date_Start;
infos.rf_ElapseTime( curDateDiff );
if (curDateDiff >= infos.rf_delay)
{
infos.rf_DelayOut();
clearInterval(infos.Interval_ID);
}
}, seconds2Check*1000, c_Delay );
return c_Delay.Interval_ID;
}
function f_DelayOut() {
outputResp.value = "time Out !"
document.querySelectorAll('#LogOn_form > input, #LogOn_form > button').forEach(e=>e.disabled=true);
}
function f_elapseTime(milliseconds) {
let timePass = Math.round( milliseconds / 1000 );
outputResp.value = `time pass : ${timePass}s / ${DelayLimit}mn`;
}
// this is the main part...
var ref_LoginDelay = f_Delay(DelayLimit, DelayChecking, f_DelayOut, f_elapseTime );
LogOn_form.onsubmit = function(e){
e.preventDefault();
if (inputName.value==='MrJ' && inputPswd.value==='MrJ' )
{
clearInterval(ref_LoginDelay);
outputResp.value = "Login success ! :)";
// your stuffs
}
else
{
LogOn_form.reset();
outputResp.value = "bad Login.. :/";
// document.querySelectorAll('#LogOn_form > input').forEach(e=>e.value='');
}
}
cancel_bt.onclick = function()
{
clearInterval(ref_LoginDelay); // = do Cancel f_Delay
outputResp.value = "Login delay disabled"
}
form { display:block; width:24em; height:12.6em; padding: 0 3em; border: 1px solid grey; margin:auto }
form > * { display:block; float:left; margin: .5em }
label, output { clear:both;}
label { width: 6em; }
<form id="LogOn_form">
<h4>Please login...</h4>
<label for="inputName" > Name : </label>
<input id="inputName" type="text"placeholder="type 'MrJ'"/>
<label for="inputPswd" > Password : </label>
<input id="inputPswd" type="password" placeholder="type 'MrJ'"/>
<button type="submit">Login</button>
<button type="reset">reset</button>
<output id="outputResp"></output>
</form>
<br> <br>
<button id="cancel_bt">Cancel Delay</button>