Javascript:SetTimeout和ClearTimeout重置。

时间:2014-03-29 15:19:27

标签: javascript asp.net settimeout cleartimeout

我有以下会话时间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上重置计数器。有人能发现错误吗?

2 个答案:

答案 0 :(得分:3)

如果您的目的是将计时器重置为初始值,那么您的所有操作都会出错。我还建议使用setInterval而不是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/

答案 1 :(得分:2)

你确实意识到你是在递归地召唤cleartime,对吧? 此外,你甚至没有打电话给cleartime。 PS也取代

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

setTimeout(DisplaySessionTimeout, 1000);