1

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.

jww
  • 97,681
  • 90
  • 411
  • 885
njeo
  • 41
  • 1
  • 7
  • 1
    What's not working? Please see [How do I ask a good question](https://stackoverflow.com/help/how-to-ask) for more information. – TylerH Nov 01 '18 at 19:58
  • TylerH this.openDialog() dialog opens the page after 2 seconds when the page loads,but i want to display the pop up when user is not accessing webpage after 5 minutes. – njeo Nov 01 '18 at 20:03
  • There is a `SyntaxError` running your Stack Snippet. – jww Nov 01 '18 at 22:18

2 Answers2

3

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

sqram
  • 7,069
  • 8
  • 48
  • 66
  • 1
    sqram,i tired to pass the model pop instead of alert i am gettting the following error.this.openDialog is not a function.can you convert the above code typescript.the above code is fine i need this typescript? – njeo Nov 01 '18 at 20:40
  • when i pressing the keybord activity it is not working – njeo Nov 01 '18 at 21:33
  • @njeo "error.this.openDialog is not a function" is a problem else - make sure you're including the file where the function is defined, or define the function in the document somewhere. And no, I've never done Typescript, but the code above is very simple, it should be easy to convert. -- also, code has been updated to fix the keypress typo – sqram Nov 02 '18 at 00:21
2

Try this:

let timer;

function time() {
timer = setTimeout(() => {
     console.log(5000)
}, 5000) 
}

time();

document.addEventListener('click', () => {
  clearTimeout(timer);
  time();
})
Kenny Horna
  • 13,485
  • 4
  • 44
  • 71