0

In the code console.log(this.gameIndex) prints out undefined. Why is this? When I console.log(this.gameIndex) within the constructor the correct value is printed out.

Typescript

export class HomeComponent implements OnInit {
  game:String;
  gameIndex;
  games:String[];
  constructor() { 
    this.gameIndex = 0;

    this.games = ['game1','game2','game3'];
    this.game = this.games[this.gameIndex];

    setInterval(this.rotatingBackground,3000);
    console.log(this.gameIndex);
  }

  ngOnInit() {


  }

  rotatingBackground():any {
    console.log(this.gameIndex);
    this.game = this.games[this.gameIndex];
    console.log(this.game);
  }


}
Peter
  • 143
  • 2
  • 11
  • You should consider changing your properties types from `String` to `string` and from `Number` to `number`, because "in JavaScript the literals are considered better" (as mentioned here https://stackoverflow.com/a/14727461) – João Ghignatti Jul 05 '19 at 05:47

2 Answers2

0

Try to use like this,

        setInterval(() => this.rotatingBackground(), 1000);
Ashish S
  • 638
  • 6
  • 14
  • Please go through this documentation, you will come to know https://javascript.info/settimeout-setinterval – Ashish S Jul 05 '19 at 12:54
0

It's because you haven't defined it.

gameIndex;

should be

gameIndex:Number;`
Kevin McCann
  • 511
  • 5
  • 13