简体   繁体   中英

Need to clear session and logout user after 30 sec or after close browser

code is in MVC and also every request are using ajax call so no change in url.

using below code i ll able to perform firt opration that logout user if user inactive of 30 sec. but not able to perform action when user logout.

<script>
    $(function () {
        $("body").on('click keypress', function () {
            ResetThisSession();
        });
    });
    var timeInSecondsAfterSessionOut = 30; // to change the session time out, change this value. Must be in seconds.
    var secondTick = 0;
    function ResetThisSession() {
        secondTick = 0;
    }
    function StartThisSessionTimer() {
        secondTick++;
        console.log(secondTick);
        if (secondTick > timeInSecondsAfterSessionOut) {
            clearTimeout(tick);
            window.location = '/Account/LogOff/0';
        }
        tick = setTimeout("StartThisSessionTimer()", 1000);
    }
    StartThisSessionTimer(); 
</script>

alse i tried the unload or beforeunload method of script but result not proper as expect.

need to logout user if user not perform any action on 30 sec or if user close browser.

thanks in advance.

as i see the var tick is local, and is defined in every tick, so the timeout is called every second:

function StartThisSessionTimer() {
             secondTick++;
             console.log(secondTick);
             if (secondTick > timeInSecondsAfterSessionOut) {
                 clearTimeout(tick);
                 window.location = '/Account/LogOff/0';
             }
             tick = setTimeout("StartThisSessionTimer()", 1000);
         }

Try to separate the initializiaton of the timeout, outside of the same scope of repeater of timeout. tell us if is useful.

Tks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM