1

hello all i am writing a code for auto logout for inactivity for about 20 minutes which should interact with keyboard as well as mouse and i have following code which works for most of the function but it is not resetting the timer for mouse movement and keyboard activity.

var timoutWarning = 9000; // Display warning in 14 Mins.
var timoutNow = 9000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = 'logout.php'; // URL to logout page.

var warningTimer;
var timeoutTimer;

// Start warning timer.
function StartWarningTimer() {
    warningTimer = setTimeout("IdleWarning()", timoutWarning);
}

// Reset timers.
function ResetTimeOutTimer() {
    clearTimeout(timeoutTimer);
    StartWarningTimer();
    $("#timeout").hide();
}

// Show idle timeout warning dialog.
function IdleWarning() {
    clearTimeout(warningTimer);
    timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    $("#timeout").show();
}

// Logout the user.
function IdleTimeout() {
    window.location = logoutUrl;
}
$( document ).ready(function() {
    StartWarningTimer();
});
$('html').mousemove(function() {
    ResetTimeOutTimer();
});

i want the code should intract with mouse movement and keyboard press all kind of help is appreciated please suggest me something

Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
sonam Sharma
  • 548
  • 12
  • 30
  • You may want to have a look at `onmousemove` http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove and `onkeypress` http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeypress – Nikhil Vartak Dec 23 '15 at 09:28
  • Please spellcheck your title. –  Dec 23 '15 at 09:30
  • Possible duplicate of [Javascript auto logout code](https://stackoverflow.com/questions/23023916/javascript-auto-logout-code) – Luciano Bargmann Nov 26 '19 at 13:16

1 Answers1

2

At first, you should not use setTimeout this way - inactive tabs getting slower, so there's no guarantee that your code will be executed in 14 minute. The better way to do that is to check repeatedly the elapsed time.

var startTime = +new Date();
function checkForWarning () {
    if (+new Date() - startTime > maxInactiveTime) {
        // show warning
    }
}

You can track activity this way:

$(document)
    .on('click', ResetTimeOutTimer)
    .on('mousemove', ResetTimeOutTimer);

Hope it helps.

Community
  • 1
  • 1
Martin Schulz
  • 582
  • 1
  • 3
  • 13
  • You have to calculate the elapsed time by difference between current time and the moment you start counting. that's the reliable way. And that's what my code does - we remember the moment we started in startTime. Then goes the method (checkForWarning) that checks whether time is out or not. We should call it repeatedly, like this setTimeout(checkForWarning, 1000 * 60) – Martin Schulz Dec 23 '15 at 14:20