0

I want to logout properly when browser is inactive with setInterval() function. When browser is active, setInterval is not counting. However, when browser stays idle then the function is counting.

How do I achieve setInterval counting even browser is active?

JavaScript

function session_checking() {
    $.post("activitytime.php");
}   
*//Every after 7 mins (60*7) after browser is inactive run activitytime.php*'   
setInterval(session_checking, 1000*10);

PHP

<?php
session_start();
//Do the necessary database update
session_destroy();
user3181614
  • 145
  • 8
  • 1
    Best practice would be to check and invalidate the session on backend when the user reloads the page. Javascript could be simply blocked through developer's console. – Kevin Kopf Apr 14 '19 at 02:03
  • `When browser is active, setInterval is not counting` why isn't it counting? it should be calling session_checking every 10 seconds regardless. And what does it mean by the browser is `active` or `idle` – Jaromanda X Apr 14 '19 at 02:03
  • 1
    Use session timeout, not javascript. [See this](https://stackoverflow.com/a/1270960/7644018) – Paul T. Apr 14 '19 at 02:04
  • @JaromandaX I assume he means no mouse movement, no typing and no scrolling... OP also disregards the fact, that javascript can't tell if the right tab is open. Seems like duplicate of [this](https://stackoverflow.com/questions/1009260/how-can-i-detect-with-javascript-jquery-if-the-user-is-currently-active-on-the-p) – Kevin Kopf Apr 14 '19 at 02:05
  • @AlexKarshin - I don't assume to know anything other than what is stated in the question - OP alleges the setTimeout isn't running while the browser is `active` - that makes zero sense, hence why I asked what he means by active and idle – Jaromanda X Apr 14 '19 at 02:08
  • True, I read it very carefully once more and now it makes zero sense to me too. Sorry for misleading you like that :) – Kevin Kopf Apr 14 '19 at 02:09
  • Possible duplicate of [How can I detect with JavaScript/jQuery if the user is currently active on the page?](https://stackoverflow.com/questions/1009260/how-can-i-detect-with-javascript-jquery-if-the-user-is-currently-active-on-the-p) – Lux Apr 14 '19 at 02:56

1 Answers1

1

You can use ´window´ events and ´clearInterval´

var sessionTimer;

function startTimer(){
      sessionTimer = setInterval(session_checking, 1000*10);
}
function stopTimer(){
    if(sessionTimer){
        clearInterval(sessionTimer);
    }
}
function session_checking() {
     $.post("activitytime.php");
} 
//means tab is active
window.onfocus = function () { 
   stopTimer(); 
}; 
//means tab is passive
window.onblur = function () { 
    startTimer();
}; 

Also if you want to call API when window is closing you can call

window.onbeforeunload = function(e) {
      //call api here
      return true;
};
Mehmet Otkun
  • 1,374
  • 9
  • 22