鼠标事件侦听器中的超时函数,但正在更新全局变量



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

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

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

Javascript函数中的

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

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

最新更新