我正在创建一个通过单击鼠标即可激活的功能,但随后无法使用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”吗?
this
关键字指函数的范围。要使用成员变量,请使用箭头函数。尝试以下]]
setTimeout(() => { // <-- use arrow function here
this.active = true;
console.log("3: " + this.active);
//Prints as true after 10 seconds
}, 10000);