Functions in JSLogo can be repeated continuosly or a set number of times. This is done with the control structures of repeat
and loop
.
The repeat
command takes a single argument, the number of times the repeat should run, and is followed by square brackets. In many cases it can be useful to use a counter variable while doing this.
make "counter 0
repeat 4 [
make "counter :counter + 1
print :counter
]
Result:
1
2
3
4
The loop
command takes no arguments and is followed by square brackets. This will repeat a set of commands indefinitely.
loop [
print 'running'
wait 5
]
Result:
running
running
running
running
//this continues forever
It's possible to end a loop or repeat with the break
command. This will stop the current loop.
loop [
print 'running'
if :condition = true [
break
]
]
Result:
running
running
The wait
command, used in above examples, waits the provided number of deciseconds (wait 10 = 1 second). Note that due to the way browsers handle throttling wait does not work reliably when the tab or window running LbyM is not in focus.