Search code examples
javascriptfunctionsetinterval

Javascript setInterval function not setting alpha every second



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.


Solution

  • 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();