0

export class Lightning{
    constructor(game){
        this.game = game;
        this.width = 640;
        this.height = 480;
        this.alpha = 0.0;
    }
    update(){
        //should cause lightning incrementally
        setInterval(function() {
            this.alpha += 0.1;
            console.log("hi");
        }, 1000);
    }
    draw(context){
        context.fillStyle = "rgba(255, 255, 255, " +this.alpha+ ")";
        context.fillRect(0, 0, this.width, this.height);
    }
}

Was expecting alpha to increase slightly once every second but this does not happen. From the main script I correctly call the import and instantiate the object and call update and draw successfully. In fact if I console.log("hi"); it says "hi" after one second so I don't get what is going on here.

Jleger91
  • 13
  • 3
  • [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484/283366). _TL;DR_ use an arrow function... `setInterval(() => { this.alpha += 0.1; }, 10000)` – Phil Jul 04 '23 at 23:12

1 Answers1

-1

Use an arrow function to preserve this properly:

setInterval(()=> {
            this.alpha += 0.1;
        }, 10000);

DEMO:

class Lightning {
  constructor(game) {
    this.game = game;
    this.width = 640;
    this.height = 480;
    this.alpha = 0.0;
  }
  update() {
    setInterval(() => {
      this.alpha += 0.1;
      console.log(obj.alpha); //0.1, 0.2 will be updated every 1 sec
    }, 1000);
  }
  draw(context) {
    context.fillStyle = "rgba(255, 255, 255, " + this.alpha + ")";
    context.fillRect(0, 0, this.width, this.height);
  }
}
const obj = new Lightning('Test');
obj.update();
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
  • Thank you, this gets the code to work. For instance now call makeLightningStrike() from within setInterval using the arrow function and it works once after the set amount of time. However, the setInterval does not happen again and again so makeLightningStrike() only gets called once. – Jleger91 Jul 04 '23 at 23:52