Peasant problems; Sarven Siege ; Javascript

I summon peasants and they do their jobs, but I continue making them indefinitely. Suggestions?

this.peasant = function(){
    if(this.gold > this.costOf("peasant")){
        this.summon("peasant");
    }
    var targets = this.findByType("peasant");
    if(targets){
        for(var i = 0; i < targets.length ; i++){
            var target = targets[i];
            var nearest = target.findNearest(this.findItems());
            this.command(target, "move", nearest.pos);
        }
        
    }
    
};

loop {
    var peasants = this.findByType("peasant");
    while (peasants.length < 2) {
        this.peasant();
    }
    
    
}

You find the number of peasants with var peasants = this.findByType("peasant");, but that doesn’t get a chance to get updated, and so the while loop will run indefinitely! There are a couple ways to fix this: you put the var peasants = this.findByType("peasant"); in the loop, or you could change the while to an if.