Jaime Ocampo
Jaime Ocampo

Reputation: 67

How to instantiate objects that use setInterval in javaScript?

I am trying to define a function in javaScript that starts a setInterval. Here is a very simple example:

var myApp = {};

myApp.test = function(name, start) {
    this.name = name;
    this.value = start;
    selbst = this;
    this.timerId = setInterval(function() {
        console.log('Interval for :' + selbst.name);
        selbst.value++;
        console.log('Name: ' + selbst.name + ', new value: ' + se`enter code here`lbst.value);
        selbst.start++;
    }, 1000);
}

If I instantiate one object this works perfect:

$(document).ready(function() {
    new myApp.test('Test1', 0);
});

However, when I define two objects

$(document).ready(function() {
    new myApp.test('Test1', 0);
    new myApp.test('Test2', 100);
});

only the second object has the setInterval started! Why is that? I wan that both objects, that are referring to the same class, have their own Interval. Why is the second setInterval overriding the first? I am using class fields, they should be independent!

Please help...

Upvotes: 0

Views: 114

Answers (1)

VisioN
VisioN

Reputation: 145398

From what I see, you have selbst variable defined globally, so on each test method call, selbst will always refer to the last myApp object instance. Defining selbst locally should do the job:

var selbst = this;

Upvotes: 3

Related Questions