Gareth Lewis
Gareth Lewis

Reputation: 751

setTimeout doesn't work after using clearTimeout

We have a form on our website in which a user can fill out and submit. Sometimes, they take longer to fill out the form than our 20 minute session timeout.

So, I have written functionality to pop up a message 2 minutes before timeout to warn the user, with an option to save and continue (which renews the session). If the warning is left, it will Autosave their work and log them out after 2 minutes.

If the message is ignored, it Autosaves the work and logs them out fine. If they click save and continue it saves fine, and the message pops back up after a further 20 minutes (while testing I've reduced the time), however, subsequent times, it does not log them out after a further 2 minutes if it's ignored.

Here is the JavaScript I have written. Can anyone see any issues?

init(); is called onLoad in the <body> tag.

var logoutTimer = setTimeout('saveAndLogOut();', 1000 * 60 * 1.5);

function init() {
    setTimeout('expirationWarning();', 1000 * 60 * 1);
    logoutTimer;
}

function expirationWarning() {
    $('#session-expiry-warning').dialog({ 
        show: 'fade', 
        hide: 'fade',
        title: 'Your session is about to expire...',
        buttons: { 
            "Save and Continue": function() { 
                ajaxSave('saved');
                clearTimeout(logoutTimer);
                init();
                $(this).dialog("close");
            }
        },
        width: 550,
        closeOnEscape: false,
        open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }            
    });
}

function saveAndLogOut() {
    ajaxSave('autosaved');
    setTimeout("parent.document.location.href = '../logout.asp';", 5000);
}

Thanks in advance.

Upvotes: 1

Views: 696

Answers (2)

Florian Margaine
Florian Margaine

Reputation: 60835

Firstly, don't use strings in the setTimeout function. Prefer the following:

setTimeout(saveAndLogOut, time)

Secondly, as @David said, your setTimeout is not called when you display the logoutTimer variable in the init() function. It looks like you want the following:

var logoutTimer = function() { setTimeout( saveAndLogOut, 1000 * 60 * 1.5 ) }

// Then, in your init function:
logoutTimer()

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129832

logoutTimer is only set once, in the first line of code that you've pasted. If the user clicks "Save and Continue", logoutTimer will be cleared. At no point will it be set to anything again.

Did you intend to set the timer in init()? It currently just says logoutTimer; there, which doesn't really do anything. If you want the timer to be re-set at this point, you would need to include the entire setTimeout command in init.

Upvotes: 2

Related Questions