How to make an accurate "repeating" script?

I want to make a “swinging” brick that swings in a certain time, I have the script for the brick, but it’s not accurate

the issue is the repeating times does not accurate

I have recalculated the timing several times, and the result is nothing wrong, all I can do is just do a test directly in the game even though it’s still does not accurate, not in the studio

so every time the brick swings, the duration is 2 seconds, for example I want to make the brick swing for 60 seconds, I type : (this is just an example, not the actual script I’m using in the game)

local a = Instance.new("IntValue", game.Workspace)
repeat
script.Parent.Orientation = Vector3.new(-8,0,-90) 
wait(2)
until a.Value == 30 --swinging for 60 seconds

script.Parent.Orientation = Vector3.new(-8,0,-90) 
wait(10) --stop swinging for 10 seconds

when I run the script, the repeating times can be more or less than 60 seconds, which means I have to do several tests in the game until the brick swaying for 60 seconds

1 Like

When do you increment ‘a’? And by how much each cycle?

every 2 seconds , and by 1 for each cycle

why not do a loop with an accurate wait time

local a = 0
local OSClock = os.clock()

repeat
    game:GetService("RunService").Heartbeat:Wait()
    if os.clock() - OSClock >= 2 then
        script.Parent.Orientation = Vector3.new(-8,0,-90)
        a += 2
        OSClock = os.clock()
    end
until a >= 60

that is probably doing to much but that is very accurate
honestly i recommend using a custom wait instead of all that

example

local sleep = require(the directory to the custom wait module)
local a = Instance.new("IntValue", game.Workspace)

repeat
    script.Parent.Orientation = Vector3.new(-8,0,-90) 
    sleep(2)
until a.Value == 30 --swinging for 60 seconds

all I did was replace the wait with the custom wait(if you want me to show the link instead of hyperlinking it here it is - Custom wait - the best solution to yielding!)

hope I was somewhat helpful

You could try a for loop?

-- runs 60 times and waits 1 second each time
for i = 1, 30 do
   script.Parent.Orientation = Vector3.new(-8,0,-90) 
   wait(2)
end

And it also looks like you are setting the parts Orientation to the same value every time? Is that what you are going for?

I added this only to not make the loop freeze the game, honestly I don’t recommend this if someone has bad frames(it runs every frame), it will ruin the waiting

just use that custom wait instead lmao

they want to run code 30 times every 2 seconds
not run code 60 times every 1 second

I think I fixed it for what he wants, let me know if it needs any more changes though!

this script works as I expected, thank you for solving my problem!