Heartbeat and keeping track of time

I’m mainly asking if something like this would end up slowing down my game and if there’s a more efficient way of keeping track time.

local heartbeat = game:GetService("RunService").Heartbeat
local duration = 5
local timeStarted = tick()
local connection

connection = heartbeat:Connect(function()
  if tick() - timeStarted > duration then
    -- run function here
    connection:Disconnect()
  end
end)

Also keep in mind duration is able to be changed from any other script.

All input is appreciated so please do share if you have something to say :slight_smile: thanks.

So you want to wait until 5 seconds have passed and then run a function? That shouldn’t cause too much lag, unless you had many of these functions. Unless it needed to be extremely precise, couldn’t you just do a while wait(1) loop?

1 Like

Yeah I need it to be precise because duration can change whenever. What if duration changes to 0.5 when it was previously 1? Well now its waiting half a second too long.

I don’t think a Heartbeat timer will slow your game. Especially since it’s going on for only 5 seconds.

Anyways, the Heartbeat timer is looking good. However, I do have some suggestions.

  1. Replace tick() with os.clock()

tick() is going to be deprecated pretty soon, and os.clock() is way more accurate than tick() (according to the wiki, to 1 microsecond).

  1. Don’t localize RunService.Heartbeat

No need to localize events anymore (since Luau already does this). It is somewhat up to style, but it’s a lot more understandable if you do RunService.Heartbeat.

  1. Change
    if os.clock() - timeStarted > duration then to
    if os.clock() - timeStarted >= duration then
2 Likes