【问题标题】:Timeout function in mouse event listener but updating global variable [duplicate]鼠标事件侦听器中的超时功能但更新全局变量[重复]
【发布时间】:2020-04-02 11:02:02
【问题描述】:

我正在创建一个函数,该函数在鼠标单击时激活,但使用 setTimeout() 在 10 秒内无法再次触发。超时后,我的变量未设置为所需的布尔值。

//Called on every mouseclick
@HostListener("document:click", ["$event"])
public documentClick() {
console.log("1: " + this.active);

  //Only enter if true
  if (this.active === true) {

    //Setting active = false so user cannot enter here again
    this.active = false;
    console.log("2: " + this.active); 

    //10 seconds delay before active = true again
    setTimeout(function() {
      this.active = true;
      console.log("3: " + this.active);
      //Prints as true after 10 seconds
    }, 10000);

  }

}

一旦超时结束 this.active 设置为 true 但是当我在超时后再次单击时,“1:false”会打印到控制台,而它应该是 true?

【问题讨论】:

    标签: angular typescript mouseevent settimeout mouselistener


    【解决方案1】:

    Javascript 函数中的this 关键字指的是函数的作用域。要使用成员变量,请使用箭头函数。试试下面的

    setTimeout(() => {  // <-- use arrow function here
      this.active = true;
      console.log("3: " + this.active);
      //Prints as true after 10 seconds
    }, 10000);
    

    【讨论】:

    • 道歉,新的堆栈。不知道那是一件事
    • 在这种情况下欢迎使用 Stackoverflow。你可以在这里看到它是如何运作的:stackoverflow.com/tour
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多