How to exit a function after certain amount of execution

Hi so i have gotten stuck at trying to make my code to run a certain number of times in a row before exiting.

// findTree(); is another function
var tree = findTree();
//if we can’t find a tree.
if (tree === false){
rotateCamera();
continue;
}
im trying to make so the Camera rotates only 5times in a row and if it doesnt find any tree it will exit the code. if it do find a tree it will countinue until it doesn’t find a tree 5 camera rotatetions before it stops the code.

I don’t have a good enough insight to the whole surrounding, but you can simply keep track of a counter and loop until you met your condition.

For example:


let counter = 0;
while(counter <5) {
  counter++;
  let val = rand();
  console.log(val, counter)
  if(val < 3) {
    console.log("found it");
    break;
  }
}

// Generate some randomness for testing purposes
function rand() { return Math.floor(Math.random() * (10 - 0) + 0) }

The above will loop max 5 times or if we met another condition; in this case tested with some random numbers :slight_smile:

Hope it helps :sparkles:

1 Like

So currently your code seems to be checking for the presence of a tree once, and if it doesn’t find one rotates the camera once.

We can use a simple for loop to make the camera rotate no more than 5 times if tree is initially false. Even better, put that for loop in a function that you can call to do the camera rotations and check for a tree at any point in your code.

Here’s one way you can do that:

var tree = findTree();

var searchForTree = () => {
    rotateCamera(); // rotate once here
    for (let i = 0; i < 4; i++) {
        tree = findTree();
        // if we find a tree we exit both the loop and searchForTree function 
        // and return true indicating a tree was found
        if (tree) {
            return true
        }
        // Otherwise rotate the camera until we find a tree
        rotateCamera();
    }
    // If code reaches here, it means we exited the loop after rotating 5 times and have not found a tree
    // so we return false
    return false
}

//if we can’t find a tree.
if (tree === false) {
    var isThereATreeInSight = searchForTree() // this will be false if no tree was found after 5 rotations

    // If there was not tree found stop your code
    if (!isThereATreeInSight) {
        // ... exit the calling function or throw an error
        throw new Error('No tree was found') 
    }
}

// continue your code execution
1 Like

Awesome i just compied your whole code just to test if it would work and it actaully did! :smiley: now i will study it further thx alot :smiley:

1 Like

No problem, glad to help :smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.