Skip to content
Advertisement

How can I log out the user even if they don’t respond to JavaScript’s “confirm()”?

This was the initial code I was using:

setInterval(function(){
  r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
  if (r == true){
    window.location.href = '../logout.php';
  }else{
    location.reload();
  }
},30000);

The confirm dialog awaits action from the user. If the action is “cancel”, they remain logged in. If the action is “OK” the are redirected to the logout.php page. The issue is that if the user does not respond, they are not logged out after those elapsed 30 seconds.

Then I thought I may use two time intervals:

setInterval(function(){
  window.location.href = '../logout.php';
},60000);


setInterval(function(){
  r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
  if (r == true){
    window.location.href = '../logout.php';
  }else{
    location.reload();
  }
},30000);

but since the confirm() method halts the script, the 60000 ms is never realised. Is there a way I can get this to work?

Advertisement

Answer

Here is my suggestion

  1. start a timer that logs the user out
  2. start a graceTimer to show a link
  3. if link clicked, the timers restarts
  4. if not, the user is logged out

https://jsfiddle.net/mplungjan/t5ejs72q/

let tId, tId1;
const end = 15000, // change to whatever - 30 minutes
  grace = 3000, // 3 secs - should be 30 secs in real life
  timer = () => {
    clearTimeout(tId);
    tId = setTimeout(function() {
      // location.replace('../logout.php')
      console.log("logged out")
    }, end);
  },
  graceTime = () => tId1 = setTimeout(toggleGrace, end - grace),
  toggleGrace = () => document.getElementById("stayLink").classList.toggle("hide"),
  init = () => {
    timer();
    graceTime()
  };

document.getElementById("stayLink").addEventListener("click", function(e) {
  e.preventDefault();
  toggleGrace();
  init()
})
init()
.hide {
  display: none;
}
<a href="#" id="stayLink" class="hide">Stay logged in?</a>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement