LSP- Setup and Draw With For and While Loops Lesson
Setup and Draw with For and While Loops
We have been observing the behavior of while and for loops independently from using setup() and draw(). It is more efficient; however, to create programs using setup() and draw().
However, since the draw() method is a loop, you end up with a loop inside a loop. Look at the program below as an example. This program uses a nested for loop to iterate through each pixel and draw a random color at each (x, y) point. You can see the display continue to produce a random color at each cycle through the draw method. To slow the process down you can set a frameRate() inside the setup() function.
There are two functions used to control the draw() function loop.
noLoop() function
The noLoop() function stops Processing from continuously executing the code within draw(). If using noLoop() in setup(), it should be the last line inside the block.
Notice noLoop() is called inside the setup() method. This makes the draw method only execute one time. You should only get 25 rectangles.
loop()
If loop() is called, the code in draw() begins to run continuously again.
There may be times when you want to stop the draw method from looping using noLoop() and then restart it back looping at another point in the code. There is a function called loop() when used in the draw() function will cause it to run continuously again.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION