-2

I have the following code snippet:

if (this.y <= 0 || this.y >= screenHeight - this.h) {
    if (!this.verticalHit) {
        this.dy = -this.dy;
        this.verticalHit = true;
        setTimeout(function() {this.verticalHit = false;}, 500);
    }
}

This snippet is executed every frame and verticalHit is a property of the object where the code belongs to.

I want to modify verticalHit, as shown in the code above. However, it seems like this is overriden inside the anonymous function, and verticalHit is never going to be assigned false.

How could I solve this? Is there any way I could return from setTimeout?

George R.
  • 311
  • 2
  • 11

1 Answers1

0

You could use an arrow function or .bind(this) on the anonymous function. Currently, your this in the timeout is bound to the global object.

if (this.y <= 0 || this.y >= screenHeight - this.h) {
    if (!this.verticalHit) {
        this.dy = -this.dy;
        this.verticalHit = true;
        setTimeout(() => {this.verticalHit = false;}, 500);
    }
}

Here's another SO answer that addresses this.

Community
  • 1
  • 1
Jecoms
  • 2,558
  • 4
  • 20
  • 31