如果用户空闲一段时间,则会话超时

时间:2014-04-02 08:10:48

标签: javascript session timeout

嗨我正在注销用户,如果用户闲置1分钟并且我正在尝试将会话时间延长到onkeypress,onmousemove,onmosueout等会话超时正在发生但会话时间延长以上事件没有发生。请在这方面帮助我。 我的代码:

var InactivityTime = function () {
    var t;
    window.onload = resetTimer();
    document.onmousemove = resetTimer();
    document.onkeypress = resetTimer();
    document.onmousedown = resetTimer();
    document.onmouseclick= resetTimer();
    document.onmouseup=resetTimer();

    function logout() {
        alert("Your session has been expired.Please Re-Login to continue");      
    }

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 60000);

        // 1000 milisec = 1 sec
    }
    return {
        //main function to initiate the module
        init: function () {           
            resetTimer();            
        }   
    };
}();

2 个答案:

答案 0 :(得分:0)

您需要在init函数中注册事件监听器,如下所示:

return {
    //main function to initiate the module
    init: function () {           
        resetTimer();
        window.onload = resetTimer();
        document.onmousemove = resetTimer();
        document.onkeypress = resetTimer();
        document.onmousedown = resetTimer();
        document.onmouseclick= resetTimer();
        document.onmouseup=resetTimer();
    }
};

这些事件监听器似乎也是多余的。我会把它们减少到只有按键和鼠标移动。

调试的一个好方法是在resetTimer()函数中添加一个console.log()语句:

function resetTimer() {
    clearTimeout(t);
    t = setTimeout(logout, 60000);
    console.log("reset");
    // 1000 milisec = 1 sec
}

答案 1 :(得分:0)

function InactivityTimer(path, delay) {

  // private instance var
  var timeout;

  // private functions
  function logout() {
    alert("you've been logged out");
    window.location.href = path || "/";
  }

  function reset() {
    stop();
    start();
  }

  function start() {
    if (!timeout) {
      timeout = setTimeout(logout, delay || 60000);
    }
  }

  function stop() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  }

  // export public api
  this.start = start;
  this.stop  = stop;
  this.reset = reset;

  // init
  document.addEventListener("mousemove", reset);
  document.addEventListener("keypress",  reset);
}

现在你可以像这样使用它了

var timer = new InactivityTimer("/logout", 60000);

// maybe some other event stops the timer?
timer.stop();

// something else starts it back up
timer.start();