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 0
in the first call?