Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I use RunService.Heartbeat to make a timer?

Asked by 3 years ago

Hello. I've seen some free timer models and when I look through their scripts, those really detailed timers with 3 decimal points uses RunService.Heartbeat. I'm currently making a timer but its accuracy is only to 1 decimal point, as if its above 1 decimal point the timer would be inaccurate.

while true do
    wait(0.1)
    Time.Value = Time.Value + 0.1
end

I know this is not the most effective method. So is Heartbeat more effective and if so how can I use it to increase my timer accuracy to 3 decimal points?

Thanks for your time and I appreciate all help!

0
bruh, the past few questions that i asked from as early as 2 months ago got no answers. Do people just give up answering these days Gmorcad12345 434 — 3y

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

I'm not sure if Heartbeat is more effective or not than the while loop, but this is how I would do it:

local runService = game:GetService('RunService')

local maxTime = 1 -- when timer should end
local currentTime = maxTime

local function onFinished ()
    print('TIMER FINISHED')
end

runService.Heartbeat:Connect(function(dt)
    currentTime -= dt -- dt is delta time, which is the time between each frame

    if currentTime < 0 then 
        onFinished()
        currentTime = maxTime -- resets the timer
    end
end)

Heartbeat is only for the client, but for the server you would need something else.

Instead, we can use tick(). If we look up Tick() it returns the number of seconds (including milliseconds) from the Unix Epoch. So we can make a more accurate timer for the server using the following code.



local function startTimer (timeLength) local startValue = tick() while (startValue + timeLength) > tick() do -- do nothing wait(0.00001) end return end

The code above should be very accurate, and if you want it to be more accurate just decrease the wait() even more. But it would be very costly to do so. I am unsure of any better ways to make a timer, so correct me if I'm wrong.

EDIT: SORRY! My mistake, both would work on the server. Thanks to OfficerBrah for correcting me.

1
The top one would work on the server and the client because Heartbeat is present on both OfficerBrah 494 — 3y
0
SORRY!! Officer is right, both would work on the server, I'll edit my answer right away. movementkeys 163 — 3y
0
Thanks for taking time to answer my question! Gmorcad12345 434 — 3y
0
Thanks for taking time to answer my question! Gmorcad12345 434 — 3y
Ad

Answer this question