setTimeout无法与angular2打字稿一起使用

Poo*_*sam 0 settimeout typescript angular

这是我正在检查页面是否空闲的html代码。如果闲置了一段时间,我需要抛出不活动警报并注销用户。

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

这些函数在打字稿组件中定义,如下所示:timoutNow变量设置为10分钟。但是,每当鼠标移动或按下某个键时,屏幕就会弹出警报。为什么在显示警报之前不等待我设置的那个时间?

// 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();
  }
Run Code Online (Sandbox Code Playgroud)

Mic*_*zos 6

它应该是

this.timeoutTimer = setTimeout(this.showTimeout, <arg2>);  // correct
Run Code Online (Sandbox Code Playgroud)

代替

this.timeoutTimer = setTimeout(this.showTimeout(), <arg2>);  // wrong
Run Code Online (Sandbox Code Playgroud)

因为在后者中,您将立即调用回调函数,而不是传递引用。