0

I have developed a login page. I am saving sessionId in local storage on login and I want to clear it after some time. But that to be if someone(logged-user) not active for some time. If he is active, I don't want to clear. But I did that even he is active also, I am clearing the local storage. Please help to know how to catch he is active or not.

        localStorage.setItem('userId', data.id);
        localStorage.setItem('user', data.phone);
        localStorage.setItem('sessionId', (Math.random()*1e64).toString(36));
        var interval = setInterval(function(){
            console.log('In localStorage');
            localStorage.removeItem('sessionId');
            clearInterval(interval);
            alert('Session expired!!')
        }, (30*60*1000));
Diego Zacarias
  • 793
  • 2
  • 12
  • 22
Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62
  • 1
    Possible duplicate of [Detecting idle time in JavaScript elegantly](http://stackoverflow.com/questions/667555/detecting-idle-time-in-javascript-elegantly) – Mr.7 Oct 03 '16 at 06:42

1 Answers1

0

You can just check use a setInterval:

var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 19) { // 20 minutes
        localStorage.removeItem('sessionId');
    }
}

Answer borrowed from here

Community
  • 1
  • 1
nikjohn
  • 20,026
  • 14
  • 50
  • 86