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.costOf("peasant")){
    var targets = this.findByType("peasant");
        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) {

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.