![]() | While: Loops and Repeating Things |
Sometimes you want a computer to repeat something over and over again. A loop is used to make a computer do something more than one time.
One type of loop is the infinite loop. With an infinite loop, a computer keeps doing the same command again and again. The computer will keep repeating the command forever.
You make an infinite loop with the "while(true)" instruction. First, you type while(true). After that, you should put an opening curly brace. Then, you put all the instructions that you want the computer to repeat. Finally, you put a closing curly brace. For example, in the above program, the computer will keep telling you how great you are and how it likes you.
The computer will just keep repeating the instructions from the infinite loop forever. To get the computer to stop, you must click on the stop button.
Loops are useful for counting things. The program above starts at 1 and keeps counting. Remember to press the stop button when you want the computer to stop.
At the beginning, n is 1. The computer then shows you this. Then, it adds 1 to n, giving 2. And then, it shows 2 on the screen. Then, it adds 1 again to n, giving 3. And it shows this on the screen. And this continues again and again. By doing this, the computer is able to count numbers.
Usually, you don't want the computer to repeat something forever. In JavaScript, there is an instruction called "break." When a computer sees the break instruction, it stops repeating things.
This program uses the break instruction to count from 1 to 5. n starts at 1. Each time the loop is repeated, n goes up by 1. But when n is 5, the loop stops, and the computer says "Done."
You can also use break to stop a loop when something important happens. In this program, the computer asks you a question. It will keep asking you the same question until you give the right answer.
On the left, you need to write a program for launching a rocket. To launch a rocket, you first need to count down from 30 to 1. There is a special machine for doing the counting. You can give a "say" command to the "machine" with a number to count. You need to get the machine to say the numbers from 30 down to 1. Afterwards, you can give the "liftoff" command to the machine. If the numbers were counted correctly, the rocket will blast off to space. Use a loop to do the counting. Your code should be similar to the code for counting from 1 to 5.