When the program executes a script, not only does it execute from top to bottom but there is only one “worker” assigned to run that script. This worker is called a ‘thread.’
Because there is a single thread, it is possible to make execution halt at a location for a specified amount of time. This can be done via a ‘wait‘ function from the task library.
(Side note, I recommend running this in a play session or keeping the counter value low if you intend to paste the code into the command bar. Large counter values will cause the loop to run in the background for extended periods without a way to stop it, save exiting the application.)
local counter = 10
while counter > 0 do
print(counter)
counter = counter - 1
task.wait(1)
end
--Output: 10
--Output: 9
--Output: 8
--Output: 7
--Output: 6
--Output: 5
--Output: 4
--Output: 3
--Output: 2
--Output: 1
This prints the counter value and then halts at the wait function for 1 second before looping back around
If you leave the function argument empty or make it 0, the wait interval will be 1 “heartbeat.”
In Roblox, heartbeat is tied to frames and one frame is one heartbeat. Currently the maximum framerate is 60 frames per second on most devices.
And 1/60 = 0.016 seconds, so the shortest possible wait interval is about 16 milliseconds.
This is for a best case scenario. If a client’s machine cannot maintain 60 FPS, they will be unable to execute the loop every 16 milliseconds.
Now let’s apply this technique to the color randomizer and change the color of the part at 1 second intervals:
local part = game.Workspace.Part
local counter = 15
while counter > 0 do
part.BrickColor = BrickColor.Random()
counter = counter - 1
task.wait(1)
end