There are several methods to make a script perform an action for a set amount of time. This tutorial will cover the simplest of them. Technically, this may not work if you have wait blocks or other blocks that take up time. "Repeat until" loops only check if their condition is true between blocks, therefore adding some imperfection to this method. For example, the glide () secs to x: () y: () block will continue to run even if the condition is met true because the loop only checks between individual blocks.
Some Scratchers want a block that repeats for a set amount of time:[1]
repeat for (1) secs {
} :: control
However, this suggestion has not yet been accepted.
Wait Method
The following script counts down a variable every second until the time reaches 0. The wait block allows it to keep track of time.
when gf clicked set [time remaining v] to [5] // amount of time to run for repeat until <(time remaining) = [0]> ... // do something while there is time wait (1) secs change [time remaining v] by (-1) end
Timer Methods
This script uses the timer. It will repeat the action until the timer is greater than the set limit. It requires resetting the timer.
reset timer repeat until <(timer) > (5)> // run for 5 seconds ... end
If the timer is in use elsewhere and resetting is not possible, a variable can be used to remember the start time:
set [start time v] to (timer) repeat until <(timer) > ((start time) + (5))> // run for 5 seconds ... end
The Days Since 2000 block updates more frequently than the timer so the following can be used when more accuracy is needed:
set [start time v] to ((days since 2000) * (86400)) // 86400 seconds in a day repeat until <(((days since 2000) * (86400)) - (start time)) > (5)> // run for 5 seconds ... end