Home > Software engineering >  Angular Incremental Count inside setInterval
Angular Incremental Count inside setInterval

Time:01-20

i am starting with Ts and angular and i cant find what i am doing wrong.

I have a button in my template that start and end a counter, it logs the number and for some reason the counter stays at 0.

<body> 
      <button (click)="onStart()">Start Game</button>
      <button (click)="onEnd()">End Game</button> 
 </body>
number:number = 0;
interval:any;
onStart(){
 this.interval = setInterval(
   function() {this.number =1;}
   ,1000);
   console.log(this.number);
   }
onEnd(){
 console.log(this.number);
 clearInterval(this.interval);
 } 

CodePudding user response:

This is because of the scope, when you create anonymous function with function keyword a new scope is created and this would override the parent parent class this. So number would not be accessible with keyword this since it's not defined within function. To overcome this you can use arrow function:

  onStart() {
    this.interval = setInterval(() => {
      this.number  = 1;
    }, 1000);
    console.log(this.number);
  }

Or you can copy the parents this into another variable and use that inside your function.

  onStart() {
    const scope = this;
    this.interval = setInterval(function () {
      scope.number  = 1;
    }, 1000);
    console.log(this.number);
  } 
  •  Tags:  
  • Related