RunService.Heartbeat Timer

Hi,

So I’m wondering on how to properly create a timer using RunService.Heartbeat, which involves getting the DeltaTime, and subtracting the time with it, but from my attempts, I have never been able to set it up properly, but here is the current code I was testing with:

dur = 60 -- the duration
t = dur -- the current time
repeat
    local dt = RunService.Heartbeat:Wait() -- DeltaTime

    t = math.max(0, t - (dt/dur)) -- Sets a Limit to the number while setting the DeltaTime divided by the duration.
    print(t/dur) -- test print
until t == 0 -- will stop when this condition is met

Would this work? or am I doing something wrong?

(This is a bit vague ik. I dont have the time to complete it, which ill do later)

You need to do t - dt only, so:

    t = math.max(0, t - dt) -- Sets a Limit to the number while setting the DeltaTime divided by the duration.

No need to put parenthesis btw as divisions occur before subtractions.
1 Like
  1. Instead of using repeat and until, you can use a while loop with the condition t > 0. This makes the code more readable and easier to understand.
  2. The calculation for updating the timer should be t = t - dt, not t = math.max(0, t - (dt/dur)). This is because dt is already the time elapsed since the last frame, so you can subtract it directly from t.

It does not? repeat should be easier (if not the same) to read than a while loop.

I know. Thats what deltaTime is.

I thought Dividing it would have it run for the amount given for the Duration, but appearently that only make it slower, and was incorrect.

Thanks btw

Your welcome :). ..

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.