Poonkodi Sivapragasam
Poonkodi Sivapragasam

Reputation: 1317

setTimeout not working with angular2 typescript

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();
  }

Upvotes: 0

Views: 6509

Answers (1)

Michel
Michel

Reputation: 28359

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.

Upvotes: 6

Related Questions