How to implement auto logout in Javascript

Conceptually, you only need 1 timer running at a time. One timer that runs for 14 minutes and another that runs for another minute (15 minutes total). Once the 14 minute timer runs out, kill it and then start the 1 minute timer. If that one minute timer runs out, log the user out. If the user presses the “Stay Logged In” button, kill the 1 minute timer and restart the 14 minute timer. Rinse and repeat.

I changed your code the best I could. Hope you get the point.

// Set timeout variables.
var timoutWarning = 840000; // Display warning in 14 Mins.
var timoutNow = 60000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl="https://stackoverflow.com/questions/23023916/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").dialog('close');
}

// Show idle timeout warning dialog.
function IdleWarning() {
    clearTimeout(warningTimer);
    timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    $("#timeout").dialog({
        modal: true
    });
    // Add code in the #timeout element to call ResetTimeOutTimer() if
    // the "Stay Logged In" button is clicked
}

// Logout the user.
function IdleTimeout() {
    window.location = logoutUrl;
}

Leave a Comment