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.

1while true do
2    wait(0.1)
3    Time.Value = Time.Value + 0.1
4end

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:

01local runService = game:GetService('RunService')
02 
03local maxTime = 1 -- when timer should end
04local currentTime = maxTime
05 
06local function onFinished ()
07    print('TIMER FINISHED')
08end
09 
10runService.Heartbeat:Connect(function(dt)
11    currentTime -= dt -- dt is delta time, which is the time between each frame
12 
13    if currentTime < 0 then
14        onFinished()
15        currentTime = maxTime -- resets the timer
16    end
17end)

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.

01local function startTimer (timeLength)
02    local startValue = tick()
03 
04    while (startValue + timeLength) > tick() do
05        -- do nothing
06        wait(0.00001)
07    end
08 
09    return
10end

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