Timed For Loop

The for loop is a handy construct with some really useful shortcuts for making counting with a loop much easier. Specifically the syntax of a for loop allows you to easily:

  1. Create a counter variable (often called i)
  2. Specify the condition that determines whether or not to keep looping
  3. Dictate how the counter should be incremented

When using a timed loop in place of a for loop you will need to take care of those three tasks on your own.

Using a Timed Loop as a For Loop

Here is a comparison of the how you might replicate the behavior of a for loop with a timed loop. Both of these examples will repeat four times, print out the following into the console:

loop #0
loop #1
loop #2
loop #3

For Loop / Timed Loop Comparison

  1. The counter variable. Note that when using a timed loop the variable must be created before the loop.
  2. The exit condition. As soon as this condition is false the loop will stop repeating. A key difference here is that the for loop checks its exit condition before each repeat of the loop, which the timed loop checks the condition during each repeat.
  3. The counter pattern. This moves the counter up each repeat. Another difference here is that the for loop runs its counter pattern after each repeat, which the timed loop runs the counter pattern during each repeat.
  4. The code to repeat. In the timed loop example we've placed this in an if/else statement so that we can check whether to run the code or not in the same way that the for loop does.

Other Approaches

The example offered above is the closest match to how a for loop works, but you have the freedom to structure your timed loop however you like. Each of the following three examples will run the same four repetitions as the previous, but each one uses a different exit condition.

Found a bug in the documentation? Let us know at documentation@code.org