user2179026
user2179026

Reputation:

How to logout after 60 seconds in jquery?

I have written jquery like below lines of code

 <script type="text/javascript">

 var t;
 window.onload=resetTimer;
 document.onkeypress = resetTimer;
 document.onmouseover = resetTimer;

 function logout() {
     var answer = confirm('You will be logged out after 60 Second');
     if (answer) {
         location.href = '../login/login.aspx'
     }
     else {
         window.onload = resetTimer;
     }
 }

 function resetTimer()
 {
 clearTimeout(t);
 t=setTimeout(logout,10000) //logs out in 10 min
 }

 </script>

Now I want that If user will not confirm after 60 second, it should be loggged out after 60 seconds i.e it should be redirected to login page. Please help me !!!

Upvotes: 0

Views: 1662

Answers (1)

Barmar
Barmar

Reputation: 781068

confirm() blocks all other Javascript, so you can't cancel it when the user takes longer than 60 seconds to response.

You can do it using a jQuery UI dialog.

$(function() {
    resetTimer();
    document.onkeypress = resetTimer;
    document.onmouseover = resetTimer;

    function logout() {
        var t1 = setTimeout(reallyLogout, 60000);
        $("<div>You will be logged out after 60 seconds</div>").dialog({
            modal: true,
            buttons: {
                OK: reallyLogout,
                Cancel: function() {
                    clearTimeout(t1);
                    resetTimer();
                    $(this).dialog("close");
                }
            }
        });
    }
    var t;
    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 10 * 60000); // Logout in 10 minutes
    }

    function reallyLogout() {
        location.href = '../login/login.aspx';
    }
});

DEMO

In the demo I've changed the logout timer to 20 seconds, and the confirmation timeout to 10 seconds, so you can test it in a reasonable amount of time.

Upvotes: 4

Related Questions