Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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!

1 comment

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

1 answer

✓ Accepted answer

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.

4 comments

1

The top one would work on the server and the client because Heartbeat is present on both

0

SORRY!! Officer is right, both would work on the server, I'll edit my answer right away.

0

Thanks for taking time to answer my question!

0

Thanks for taking time to answer my question!

This discussion is preserved as it was. New answers, comments, and votes are closed.