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?

2
  • yes. it still says NaN. Commented Sep 2, 2020 at 5: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? Commented Sep 2, 2020 at 6:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked! Thank you. Can you give me a link to help me explain this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.