I am trying to make an auto-logout on inactivity using JavaScript. The thing is even when I move my mouse and rapidly press any key the timer does not reset.
var timeOut;
function reset() {
window.clearTimeout(timeOut);
timeOut = window.setTimeout( "redir()" , 5000 );
}
function redir() {
window.location = "index.php?page=Logout";
}
window.onload = function() { setTimeout("redir()" , 5000 ) };
window.onmousemove = reset;
window.onkeypress = reset;
Set the timeOut
variable in your onload
event:
window.onload = function() { timeOut = setTimeout("redir()" , 5000 ) };
Otherwise, clearTimeout
can't clear the first timer.
Also note that it's best to refer to the functions directly in setTimeout()
, like this:
window.onload = function() { setTimeout(redir, 5000 ) };
Working Snippet:
var timeOut;
function reset() {
window.clearTimeout(timeOut);
timeOut = window.setTimeout(redir, 5000);
}
function redir() {
console.log('redirected');
}
window.onload = function() {
timeOut = setTimeout(redir, 5000)
}
window.onmousemove = reset;
window.onkeypress = reset;
</div>