每秒调用 javascript 函数(近 1800 秒)设置超时和设置间隔有滞后问题



我想在会话超时1分钟之前显示登录弹出。maxsession idle超时值为1800秒(30分钟),所以我使用了一个计数器变量,例如 IDLECOUNT 。使用setInterval()我正在增加该变量值。因此,现在当变量值为1740(即我的空闲会话超时值1800-60秒)时,我将显示登录弹出窗口(有2个按钮(1)让我登录(2)登录)。问题是setInterval()无法正确维护变量 idleCount 的值。由于该登录弹出不正常工作。

当您想依靠实际到期时间时,您不应使用超时或setInterval,因为它们不可靠。另外,请注意,刷新取消Settimeout/setInterval。相反

示例:

setInterval(function(){
  var decodedToken = localStorage.getItem('user_token');
  if (decodedToken.exp < new Date().getTime()/1000) {
    // Token is expired
  }
}, 3000);

我花了几个小时为此,我希望得到感激之情。

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>

最新更新