2014-04-02 48 views
0

嗨我註銷用戶,如果用戶閒置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();    
     } 
    }; 
}(); 

回答

0

您需要在下面的初始化函數註冊事件監聽器:

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 
} 
+0

我試過這不起作用 – user3483944

+0

你有沒有嘗試過用console.log()消息添加? – Kyo

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();