[SOLVED] Help with Infinite Loop in Function in Weakest Quickest

I’m getting a “Code never finished. It is either really slow or has an infinite loop” message.

The is the code I’ve got so far:

function findWeakestEnemy(weakestEnemy) {
    var enemies = hero.findEnemies();
    var weakest = null;
    var leastHealth = 99999;
    var enemyIndex = 0;
    // Loop through enemies:
    while (enemyIndex < enemies.length){
        // If an enemys health is less than leastHealth:
        if(enemies[enemyIndex].health < leastHealth){
            // Make it the weakest 
            weakest = enemies[enemyIndex];
            // and set leastHealth to its health.
            leastHealth = weakest.health;
    return weakest;

while(true) {
    // Find the weakest enemy with the function:
    var weakestEnemy = findWeakestEnemy();
    // If the weakest enemy here:
    if (weakestEnemy){
        // Attack it!

Code written by me are the array iteration while loop and it’s conditions, and the while true loops actions. As I was typing up this post I thought to try seeing if the hero is actually seeing any enemies to begin with by using the hero.say(); method to get the hero to print to the screen the result of enemies.length

The hero sees 0 enemies at the very beginning (and is wearing the infinity lenses) which might partially explain why the shamans walk on the spot and hero just stands there defiantly, looking pretty for the player.

If I set my enemyIndex variable to -1 it seems the loop will run long enough for my hero to die a crackling smoldering death however I don’t think this is the right workaround.

I’ve also tried to get my hero to move a couple of units along the y axis, which does get the shamans further into the map however things stop and again I’m stuck in a loop, although hero can now see that there are 3 shamans.

So after all this, I’m pretty sure if this is just a bug with my code and I’m also pretty sure the problem is with my findWeakestEnemy() function and my lack of understanding on how to use functions.

Any help?


My main problem was that my iteration was in the wrong block.