3

我有以下会话时间javascript代码

    <script type="text/javascript">

    var time;
    var sessionTimeout = <%= Session.Timeout %>

    function DisplaySessionTimeout() {

       document.getElementById("<%= lblSessionTime.ClientID %>").innerText = sessionTimeout;
        sessionTimeout = sessionTimeout - 1;

        if (sessionTimeout >= 0)
            time = window.setTimeout("DisplaySessionTimeout()", 1000);
        else {
            alert("Your current Session is over.");
        }
   }

    function cleartime() {
        clearTimeout(time);
        document.onmousemove = cleartime;
        document.onkeypress = cleartime;
    }
</script>   

它可以倒计时。但是当我移动鼠标或按下键时没有任何反应。我希望它在 mousemove 和 keypress 上重置计数器。任何人都可以发现错误吗?

4

2 回答 2

3

如果您打算将计时器重置为其初始值,那么您将完全错了。我还建议使用setIntervalfor this 而不是setTimeout(并将其传递给函数而不是字符串):

var time,
    sessionTimeout = <%= Session.Timeout %>,
    remainingTime = sessionTimeout,
    intervalHandle,
    lastPos = [0, 0];

function displaySessionTimeout() {
   document.getElementById("<%= lblSessionTime.ClientID %>").innerText = remainingTime;
}

function updateTimer() {
    remainingTime -= 1;

    if (remainingTime >= 0) {
        displaySessionTimeout();
    } else {
        clearInterval(intervalHandle);
        alert("Your current Session is over.");
    }
}

function resetTimer() {
    if (remainingTime >= 0 && (e.clientX !== lastPos[0] || e.clientY !== lastPos[1])) {
       lastPos = [e.clientX, e.clientY];
       remainingTime = sessionTimeout;
       displaySessionTimeout();
    }
}

intervalHandle = setInterval(updateTimer, 1000);
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
displaySessionTimeout();

http://jsfiddle.net/2ZERB/

于 2014-03-29T15:24:16.783 回答
2

您确实意识到您正在递归调用 cleartime,对吗?此外,你甚至没有打电话给 cleartime。PS也替换

window.setTimeout("DisplaySessionTimeout()", 1000);

setTimeout(DisplaySessionTimeout, 1000);
于 2014-03-29T15:27:51.623 回答