How check idle activity using Javascript

Viewed 3202

Is there any default way in JavaScript to check user activity. If not how to address this issue.

2 Answers

There is no default way of doing this in java script. One way to address this issue is using JavaScript events.

this.lastActiveTime = new Date();
          window.onclick = function () {
                this.lastActiveTime= new Date();
             };
             window.onmousemove = function () {
               this.lastActiveTime= new Date();
             };
             window.onkeypress = function () {
                this.lastActiveTime= new Date();
             };
             window.onscroll = function () {
                this.lastActiveTime= new Date();
             };
             
          let idleTimer_k = window.setInterval(CheckIdleTime, 10000);
       
          function CheckIdleTime() {
//returns idle time every 10 seconds
                  let dateNowTime = new Date().getTime();
                  let lastActiveTime = new Date(this.lastActiveTime).getTime();
                  let remTime = Math.floor((dateNowTime-lastActiveTime)/ 1000);
// converting from milliseconds to seconds
                 console.log("Idle since "+remTime+" Seconds Last active at "+this.lastActiveTime)
          }
<div> APP Here <br/><br/><br/><br/><br/><br/>make activity here<br/><br/><br/><br/><br/>Till here </div>

Here is the short example of the functionality where something will happen if user was inactive for around 10 minutes.

Upon init of the app:

window.lastActivity = Date.now();
document.addEventListener('click', function(){
    window.lastActivity = Date.now();
})

Somewhere in particular service:

var TIMEOUT = 600000 //10 mins
var activityChecker = setInterval(check, 3000);

function check() {
    var currentTime = Date.now();
    if (currentTime - window.lastActivity > TIMEOUT) {
        // do something useful, for example logout or whatever
    }
}

This approach is nice because it doesn't depend on some timers which are working incorrectly if user minimize browser or switch to another tab, etc. We just check current timestamp with the lastActivity timestamp every few seconds. You can change 'click' event in my code with any other type of event you need or with any other condition which is suitable for you to consider user as active.

Related