0

This is the html code from where i am checking for if the page is idle. And if its idle for a while I need to throw inactivity alert and logout the user.

<div *ngIf="environmentData" xmlns="http://java.sun.com/jsf/html" (load)="startTimers()" (mousemove)="resetTimers()" (keypress)="resetTimers()">

The functions are defined in typescript component like below: timoutNow variable is set for 10 minutes. But the screen pops the alert everytime the mouse moved or a key is pressed. Why is it not waiting for that time that i have set before showing the alert?

// Start timers.
  startTimers() {
    console.log("inside start timers method");
    console.log("time out number is "+this.timoutNow);
    this.timeoutTimer = setTimeout(this.showTimeout(), this.timoutNow);
    // window.location.href = this.environmentData.logoutUrl;
  }

  showTimeout(){
    console.log("inside show timeout");
    bootbox.alert("You are being timed out due to inactivity!");
  }

  // Reset timers.
  resetTimers() {
    console.log("inside reset timers method");
    clearTimeout(this.timeoutTimer);
    this.startTimers();
  }

1 Answer 1

6

It should be

this.timeoutTimer = setTimeout(this.showTimeout, <arg2>);  // correct

instead of

this.timeoutTimer = setTimeout(this.showTimeout(), <arg2>);  // wrong

because in the latter, you are immediately invoking the callback function instead of passing the reference.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot! That worked. Cant believe that is the mistake.
Welcome:) I added the explanation for reference.
Also @PoonkodiSivapragasam you want to gain access to other functions within the class you need to either use the arrow syntax or .bind(this)
@cgatian indeed or, since there is no instance state, why not make it a function?
@cgatian I have added .bind(this) in the showTimeout method to gain access to the local variables used within the class. However, the value is still undefined. Am i missing something? Please see the code below: bootbox.alert("You are being timed out due to inactivity!", function(){ window.location.assign(this.logoutUrl)}.bind(this));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.