Marian Ivanov
Marian Ivanov

Reputation: 168

Why does this end up in an infinite loop in Javascript?

I'm making a tower desence game for a game jam in HTML5. I have a subroutine for the AI of the towers. However, for some reason, this function call without a loop ends up in an infinite loop. It only happens when there are at least two towers.

function aiTower(id){
    if(id === 1)alert("towerId = 1 call 1");
    var l = zamerajCiel(id);
    if (l !==  null) towers[id].shoot(l.x,l.y);
    if(id === 1)alert("towerId = 1 call 2");
};

The loop that calls it:

function aiLoop(){
    for(i=0;i<enemies.length;i++){
        aiMon(i);
    }
    for(i=0;i<towers.length;i++){
        aiTower(i);
            if(i === 1)alert("towerId = 1 call 3");
    }
}

The debug msgs are alternating "towerId = 1 call 1" and "towerId = 1 call 2", so the problem probably isn't in the aiLoop(). Also, I have used a regexp to search my code for aiTower(). These were the only two occurences.

Upvotes: 0

Views: 108

Answers (1)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

Make i local to the function by providing var i. It is likely that you modify it elsewhere.

Upvotes: 2

Related Questions