1
loadingPercent: number = 0;

  ngOnInit(): void {
    window.setInterval(function() {
      console.log(loadingPercent + 10);
    }, 1000);
  }

I am trying to simply add 10 every second but I get the answer NaN. I am using typescript in Angular 10. Why is simple addition so difficult?

npatel
  • 233
  • 3
  • 15
  • yes. it still says NaN. – npatel Sep 02 '20 at 05:57
  • Just for clarification, this isn't an Angular 10 issue, this is a javascript scope issue. [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Dane Brouwer Sep 02 '20 at 06:16

1 Answers1

2

What is happening is inside setInterval function? You are not accessing the class scope.

This could be solved in three ways.

Option 1:

Use arrow function for setInterval that will explicily binds the scope inside setInterval to your class scope.

ngOnInit(): void {
  setInterval(() => {
    this.increment();
  }, 1000);
}

increment() {
  this.loadingPercent = this.loadingPercent + 10;
  console.log(this.loadingPercent);
}

Working Fiddle

If you are not using arrow function, you need to bind scope manually.

Option 2

 loadingPercent = 0;

 ngOnInit(): void {
    var that = this;
    setInterval(function() {
        that.increment();
    }, 1000);
  }

increment() {
    this.loadingPercent = this.loadingPercent + 10;
    console.log(this.loadingPercent);
}

Working Fiddle.

Option 3

  loadingPercent = 0;

  ngOnInit(): void {
      setInterval(this.increment.bind(this), 1000);
  }

  increment() {
      this.loadingPercent = this.loadingPercent + 10;
      console.log(this.loadingPercent);
  }

Working Fiddle.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49