1

I would like to start a setInterval method in javascript every time I instantiate a class (I know, I shouldn't call it class in javascript, ...). The setInterval is calling the class method update every 500 milliseconds. Here is my code:

function Test(a) {
  this.a = a;
  this.b = 0;
  this.interval = setInterval(this.update, 500);
};

Test.prototype.update = function() {
    console.log(this.b);
    this.b += 1;
    if (this.b > 10) clearInterval(this.interval);
};

But when I instantiate the class with var mytest = new Test(1), the class property b seems to be undefined in the first call and NaN subsequently (because adding 1 to undefined gives NaN). Why b is not 0in the first call?

Chumo
  • 13
  • 3

1 Answers1

2

The scope of this changes when setInterval fires. this will be window. To maintain the scope, you can use bind.

setInterval(this.update.bind(this), 500);
epascarello
  • 204,599
  • 20
  • 195
  • 236