Home 14: While loops
Content
Cancel

14: While loops

First, we will have a look at while-loops. A while-loop will be executed until a condition is true. The conditions are the same as we use them in if-statements. If you want to refresh your knowledge about conditions, you can go back to the corresponding chapter.

In a first example we want to count and print out the current number in the console.

1
2
3
4
5
let count = 0;
while (count < 5) {
  console.log(count);
  count = count + 1;
}

First we define a variable called count. It will be used to count how often we have executed the action-block. Next we use the keyword while to define our while-loop. In the brackets we write the condition. You can see some similarities to the if-statement here. Our condition says that our variable count should be smaller than 5. Inside the action-block of our loop, you can now describe what should happen every time that action-block is executed. In our case we want to print out the value of our variable count with console.log and count up our variable by 1.

What to do, if p5canvas doesn’t update?

Probably you accidentaly created an endless loop, but no worries, you can just close and open p5canvas to resolve the problem. Learn more about it in this video.

This post is licensed under CC BY 4.0 by the author.
Contents