Forever loops are a form of infinite loop. Some of you might already be thinking, “Oh no! That’s a bug!”
Usually we don’t want loops to go on forever. Think back to the story of the sorcerer’s apprentice. He had a job that was boring and repetitive, and he thought: I can automate this! He cast a spell on a broomstick and told it to carry water from the well. But he didn’t know the spell to make it stop!
Infinite loops are like that spell, they go on forever. Lucky for us, Scratch is much better than the apprentice at keeping loops contained. If you want to make an animation that loops continuously, the forever loop is what you want.
Another type of loop is repeat. You may have seen this type of loop called a for loop. This loop starts off by saying how many times it should repeat.
Our repeat loop, which helps us remember the theme to the 1966 tv series Batman, repeats 13 times. Each time through the loop, our sprite says “Na” and waits. After we’ve gone through 13 times, we can finally progress past the loop and say BATMAN.
Why do we wait 0.1 seconds? Without this wait, we wouldn’t see 13 distinct “Na” lines, just one “Na” for 3.25 seconds (0.25 * 13).
You can see this code in action on Scratch.
Another type of loop is the repeat until loop. This loop will run until a condition is met. This code tells the monkey to glide around the screen at random until it reaches the bananas.
Unlike the repeat loop in our last example, we don’t know how many times the loop will repeat — our monkey is just too unpredictable! But with the repeat until loop, we don’t have to.
Before entering the loop, we check if we’re touching the bananas. If we are, we can skip the loop. If not, we enter the loop and glide for 1 second to a random position, then go back up to the top and check again.
After the loop is finished, our monkey says “Bananas!” for two seconds and then returns to his starting position.
You can see our monkey in action on Scratch.
- Intro to Scratch Programming
- Intro to Scratch Programming: If/Else and Variables
- Intro to Scratch Programming: Loops
- Advanced Scratch: Broadcasts
- Advanced Scratch: Custom Blocks and Extensions (Make your own music!)
- Resources for Young Coders