Help with infinite loop in cloudrip brawl7 (JavaScript)

here is my code

function onSpawn() {
    while(true) {
        var enemy = hero.findNearestEnemy();
        var enemies = hero.findEnemies();
        if (enemy) {
            if (pet.isReady("shape-shift") && enemies.length > 5) {
                pet.shapeShift();
            } else {
                pet.moveXY(119, 39);
            }
        }
    }
}


hero.moveXY(61, 19);
hero.moveXY(108, 9);
pet.on("spawn", onSpawn);
while(true) {
    var enemy = hero.findNearestEnemy();
    var witch = hero.findNearest(hero.findByType("witch"));
    if (witch && hero.distanceTo(witch) < hero.attackRange) {
        hero.scattershot(witch);
    }
    if (enemy && hero.distanceTo(enemy) < hero.attackRange) {
        hero.scattershot(enemy);
    }
    if (hero.canCast("earthskin")) {
        hero.cast("earthskin", hero);
    }
    if(hero.isReady("throw") && enemy && hero.distanceTo(enemy) < hero.throwRange) {
        hero.throw(enemy);
    }
    if(hero.isReady("heal") && hero.health < 2001) {
        hero.heal(hero);
    }

    if(hero.gold >= hero.costOf("paladin")) {
        hero.summon("paladin");
    }
    var friends = hero.findFriends();
    for(var i=0; i < friends.length; i++) {
        var friend = friends[i];
        if (friend && friend.type == "paladin") {
            var target = friend.findNearestEnemy();
            if (friend.canCast("heal") && hero.health < 1300) {
                hero.command(friend, "cast", "heal", hero);
            } else {
                hero.command(friend, "move",{x: hero.pos.x-3, y: hero.pos.y});
            }
        }
    }

}

What is your hero?
I think infinite loop can be because of lots of ogres on 7.

I avoid using hero in on theSpawn() when an alternative is available. I encountered nasty freezing when doing it and I suspect, but cannot point the exact cause. Will be happy to be explained how the main while loop and pet.on(“spawn”, onSpawn) work simultaneously.
So

        var enemy = hero.findNearestEnemy();
        var enemies = hero.findEnemies();

will be

        var enemies = pet.findEnemies();
        var enemy = pet.findNearest(enemies);