Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I preform a certain action a certain amount of times in 1 second evenly split out?

Let's say I want to preform an action 15 times in a second. I want to make sure the action was preformed exactly 15 times in exactly 1 second. How do I do that?

I've tried this:

local oldTime = os.time();
local amount = 15;
local iteration = 1;

while os.time() == oldTime do
	wait(1 / amount);
	iteration += 1;
end;

print(iteration)

If you don't know what it does, there is a loop that only lasts for 1 second, and it waits 1 15th of a second and adds 1 to a variable until a second has passed

But when I print the variable that was supposed to be 15 from adding, it's almost never 15.

By evenly split out, I mean I want the action to be done all at the same time, I want the actions to be done split evenly out the second.

(I'm doing a different action, not increasing a variable. I just did that for the example)

2 answers

✓ Accepted answer

This can be achieved with a for loop.

A for loop runs code a certain amount of times, and to wait in-between you just use wait().

local amount = 15;
local iteration = 0;

for count = 1,amount do
    wait(1 / amount);
    iteration += 1;
end;

print(iteration)

In this example it runs your code 15 times. Adding 1 to the "iteration" variable every 1/15 of a second. Also I set iteration to 0 because it ran 15 times and iteration would be 16 if it started as 1. Hopefully I didn't misunderstand and hopefully it helped!

You can learn more about for loops here: https://developer.roblox.com/en-us/articles/Loops

1 comment

0

It worked, although I know what a for loop does, no need to explain it to me. I'll mark it as an answer when I figure out how. Nevertheless, you are a legend, thanks.

Using os.time() == oldTime is very unreliable, as the oldTime could be something like 100000.5 and os.time() could be 100001. Meaning, it has only .5 seconds to take those 15 actions.

There's a simple solution to this. You just add + 1 second to oldTime and check if os.time() is lower or equal to oldTime.

As for the 15 actions, you need to check if iteration == 15.

local oldTime = os.time() + 1;
local amount = 15;
local iteration = 0;

while os.time() <= oldTime do
    wait(1 / amount);
    iteration += 1;
	if iteration == 15 then
		break
	end
end;

print(iteration)

3 comments

0

It sometimes returns 14 and I've added some testing code and figured out it's done in 2 seconds.

0

I don't care about the 2 seconds part, but if it doesn't do it 15 times it's unreliable for me.

0

That's weird, unless you have some kind of code that delays the loop. Other than that, this is the approach you should take.

This discussion is preserved as it was. New answers, comments, and votes are closed.