Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: SetTimeout and ClearTimeout reset.

I have this following session time javascript code

    <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>   

It's able to count down. But nothing happends when i move the mouse or pressing on key. I want it to reset the counter on mousemove and keypress. Can anyone spot the error?

like image 780
user3346509 Avatar asked Apr 25 '26 01:04

user3346509


2 Answers

If your intention is to reset the timer to its initial value, then you're going about it all wrong. I also recommend using setInterval for this rather than setTimeout (and passing it a function rather than a string):

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/

like image 175
JLRishe Avatar answered Apr 27 '26 14:04

JLRishe


You do realise you are calling cleartime recursively, right? Also, you are not even calling cleartime. PS also replace

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

with

setTimeout(DisplaySessionTimeout, 1000);
like image 37
Wazzaps Avatar answered Apr 27 '26 14:04

Wazzaps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!