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?
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/
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With