spawn(function()
while User do
wait(5)
end
end)
spawn(function()
while User do
wait()
end
end)
I have 2 loops, but each one has a different wait time set, for specific reasons. I am wondering is there a way to combine them both so it’s just one, and have the code from the wait() run constantly and the code inside the wait(5) have to wait 5 seconds before running again.
You could use some conditional logic so that you increment a timeElapsed variable, and check if timeElapsed > 5 to run your five second loop and reset timeElapsed
You could try having a manual counter for activating the 5 second loop while the tiny loop is firing, although it won’t be that exact, which you probably wouldn’t have to worry about.
The wait function returns two values, that being the time that passed since you called wait and how much time passed in the game or something, and the first value is very useful. You could add time from the first value to a counter, and once it reaches 5, you execute whatever is supposed to happen at that time and reset that counter back to 0:
--first iteration:
spawn(function()
while User do
loop5()
wait(5)
end
end)
spawn(function()
while User do
loopContinuous()
wait()
end
end)
--second iteration
spawn(function()
local i = 0
while User do
i = i + wait()
loopContinuous()
if i >= 5 then
i = 0
loop5()
end
end
end)
Note: This only works because the wait time for a wait() is so small that it is unnoticeable if there is lagtime in-between. Mathematically speaking, this only works because 5 is a multiple of 1/30 and is also unnoticeable in the bigger scheme of whole seconds, while bigger numbers may not have this benefit.
This means that a loop like this would have obvious differences in time:
--don't do this!
spawn(function()
local i = 0
while User do
-- this will be incremented in units of 4 instead of 1/30!
i = i + wait(4)
loop4()
if i >= 5 then
i = 0
loop5()
end
end
end)
3 Likes
How can I do that tho? As this would not work, and I’m not sure how many ‘seconds’ are in just a wait()
while User do
timeElapsed = timeElapsed + 1
if timeElapsed == 5 then
-- Do the wait(5) loop
end
wait()
end
1 Like
In a wait, there is almost exactly 1/30 seconds that pass because of Roblox’s task scheduler per loop, so you could just increment timeElapsed by 1/30 each loop.
You might not want to use == to compare by the way, since you will be getting float calculation errors over time. You can just multiply 5 by 30 and increment timeElapsed by 1 each loop to circumvent this problem, however.
1 Like
A robust method of determining how long a wait() is would be to use its return value(s). The first is the elapsed (waited) time and the second is the time since the application started, as seen on the wiki. Just increment the time by the elapsed time after each wait. Then you can subtract 5 from it if it is greater than or equal to five.
1 Like