Petr Petr - 9 months ago 28
Javascript Question

How get setInterval for every objects?

Subj

I have javascript code, example

var User = function(data){
this.name = data.name;
this.delay = data.delay;
this.say();
}

User.prototype.say = function(){
_self = this;
setInterval(function(){
console.log(_self.name);
}, this.delay * 1000);
}



var u1 = new User({name: "user1", delay: 10});
var u2 = new User({name: "user2", delay: 15});


u1 and u2 object returns user2.

How return user1 through 10 seconds and return user2 through 15 seconds ?

Answer Source

This happens because of how closures work. You are not creating a new copy of _self for each setInterval as you are thinking because the variable is in the global scope, so the last one created overwrites the first value.

Try this:

var User = function(data){
  this.name = data.name;
  this.delay = data.delay;
  this.say();
}

User.prototype.say = function(){
  var _self = this;
    setInterval(function(){
      console.log(_self.name);
  }, this.delay * 1000);
}

var u1 = new User({name: "user1", delay: 10});
var u2 = new User({name: "user2", delay: 15});

Each call to the anonymous function creates a new local scope, which is new for each closure created within it, and thus, each scope has it's own value for _self when you add var before it.

Consider looking at the documentation of Bind() as well.