0

I am creating a function that is activated on mouse click but then cannot be triggered again for 10 seconds by using setTimeout(). After the timeout, my variable is not set to the desired boolean.

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

  }

}

Once the timeout finishes this.active is set to true but when I click again after the timeout, "1: false" is printed to the console when it should be true?

Gary Kelly
  • 43
  • 1
  • 8

1 Answers1

0

this keyword in a Javascript function refers to the scope of the function. To use member variables, use arrow functions. Try the following

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