javascripthtmluser-inactivity

Show popup when user is inactive after 5 minutes


I am trying to show pop up when the user is inactive for 5 minutes.

  timeout() {
    setTimeout(() => this.openDialog(), 4000);
 }
<h2 mat-dialog-title>Alert!</h2>
<mat-dialog-content class="mat-typography">
</mat-dialog-content>
<mat-dialog-actions align="end">
  <button mat-button mat-dialog-close>Cancel</button>
  <button mat-button [mat-dialog-close]="true"cdkFocusInitial>Ok</button>
</mat-dialog-actions>

In the code above the this.openDialog() dialog displays when you open the page after 2 seconds. But I want to display the pop up when user is inactive for 5 minutes.


Solution

  • Have a variable that will track the number of milliseconds user hasn't done any activity

    Check for any mouse or keyboard activity - reset timer to 0 when it happens Here's an example that will wait 5 seconds instead of 5 minutes

    var idleTime = 0
    
    document.addEventListener('mousemove', resetIdleTime, false);
    document.addEventListener('keypress', resetIdleTime, false);
    
    function resetIdleTime ()
    {
        idleTime = 0    
    }
    
    
    function checkIfIdle ()
    {
      idleTime += 1000
      console.log(idleTime)
      if (idleTime >= 5000)
      {
        alert("Inactive for 5 seconds")
        clearInterval(idleInterval)
      }  
    }
    
    var idleInterval = setInterval(checkIfIdle, 1000);
    

    Question wasn't that clear. Are you trying to check if the tab hasn't been focused on in 5 minutes? inactive on page for 5 minutes? either way, the above should point you in the right direction