2

I need to create multiple simultaneous animated objects with different speed frequencies using setInterval and generated by the same constructor. The problem that I'm facing is that after creating 2 or more objects, the object's method passed to setInterval have always a reference to the last object created. Bellow is an example of what I'm trying to achieve:

function obj(s){
    this.speed = s;
    this.colors = ["FF0000","FF3300","FF6600","FF9900","FFCC00","FFFF00","FFCC00"];
    _this = this;
    this.counter = 0;

    this.genDiv = function(){
        this.div = document.createElement('div');
        this.div.style.width = 100 + "px";
        this.div.style.height = 100 + "px";
        document.body.appendChild(this.div);
        setInterval(function(){_this.div.style.backgroundColor =  "#" + _this.colors[_this.globalCounter()]}, _this.speed);
    };

    this.globalCounter = function(){
        if(this.counter <= (this.colors.length-1)){
            return this.counter++;
        }else{
            this.counter = 1;
            return 0;
        }
    };
}

window.onload = start;

function start(){
    var a = new obj(1000);
    var b = new obj(2000);
    a.genDiv();
    b.genDiv();
}

After running this code, both setIntervals calls are animating only the object b. Using simple functions it works fine but I want a self content animated objects which can be populated and run independently. Thanks.

1 Answers1

2

You missed the var when you define _this. Without it's a global variable and overwritten with the next new object.

var _this = this;

should fix it.

Andreas
  • 1,622
  • 14
  • 13