[Solution] How to use this in setInterval and setTimeout problems inside objects

| No Comments »

Problem: One of the problems we find when using setInterval and setTimeout functions in javascript is how the special variable this is switched to the window object on the instance the function executes inside the interval.

Answer: Store the current object in a variable (for this example, the variable is called self) and use that variable for your interval’s function instead of this.

function foo()
{
this.init = function () {
var self = this;
this.interval = setInterval(function(){ self.update(); }, 1000); // this can be setTimeout
};

this.update = function () {
this.counter++;
console.log(this.counter);
};
}

Json Example



Leave a Reply