The for loop does not run like I would expect it to. I would expect the for loop to run only once, but when I run it, it shows an animation.
The programming environment I am using: https://www.khanacademy.org/computing/computer-programming/programming/arrays/pp/project-make-it-rain
var xPositions = [200];
var yPositions = [0];
draw = function() {
background(204, 247, 255);
for (var i = 0; i < xPositions.length; i++) {
noStroke();
fill(0, 200, 255);
ellipse(xPositions[i], yPositions[i], 10, 10);
yPositions[i] += 5;
}
};
When we say i++
then the condition i < xPositions.length
is no longer true.
So why does the the loop run more than once?
I was told that because the draw function is called forever, the loop will also get called forever.
But, the second time the loop tries to run, the condition of the for loop is not met and therefore should not run.
Thanks.
Blockquote
.
Blockquote
I would expect the for loop to run only once
This is the correct expectation...with one addtion: the for loop will only run once per function call. If draw()
is called more than once, then it will execute the loop every time you call the function.
draw()
creates a single frame of the animation. In this case, you move the rain drop down 5 pixels and then render the frame with it at the new position. But to get the animation, you need to call draw()
several times a second. This is similar to flipping the corners of your notebook with a slightly different version of a stick man drawn on each page to create an illusion of motion. The repeated calls to draw()
are taken care of in your programming environment.
The for loop you write inside of draw()
is intended to iterate over each raindrop. In this case, you only have one. I suggest adding 3 or 4 raindrops at different positions. Then you will see how the for loop iterates over each raindrop, moving them each down 5 pixels. Then your programming environment on Kahn Academy will call draw()
several time per second for each frame in the animation.