Creating a cooldwon timer with milliseconds

Hello i wanted to create a timer but the problem is it’s very unacrurate the timer finishes just after you can use my ability but i want to it to finish at the same time that the cooldown stops for my ability i also tested the time but in seconds instead and it was more accurate it only has a one second delay compared to the old one that has a 5 second delay

Here’s the script that i use for the timer in milliseconds :

local start = os.time()
for i  = 35 * 10 , 1 ,-1 do -- 35 is the cooldown time in seconds
	task.wait(0.1)
	
	print((i / 10).."s")
end

print(os.time() - start) -- Prints 40 

And the one in second :

local start = os.time()
for i  = 35, 1 ,-1 do -- 35 is the cooldown time in seconds
	task.wait(1)
	
	print(i.."s")
end

print(os.time() - start) -- prints 36

Something like this should work:

local function GetTime()
	return workspace:GetServerTimeNow()
end

local StartTime = GetTime() --Gets the starting time
local TimerSeconds = 35 --How many seconds should the timer run for

repeat

	print(StartTime  + TimerSeconds - GetTime(), "s")
	--StartTime + TimerSeconds is the max time, and we subtract the current time
	--from the max time to get the remaining time

	task.wait() -- task.wait() so the code doesn't crash
until StartTime + TimerSeconds < GetTime() --And the timer ends when the max time is smaller than the current time
2 Likes

And you can use this function to print only x decimals:

local function FormatNumber(Number, DecimalCount)
	return string.format("%."..DecimalCount.."f", Number)
end

print(FormatNumber(15.34635574, 3)) -- prints 15.346

More about string.format:

2 Likes

Do you know why my script is so unaccurate ?

1 Like

Because task.wait(x) doesn’t wait exactly x time it waits a little bit longer than x

And I think the reason for that is roblox runs at 60 fps and it checks if it should stop waiting every frame. For example when you do task.wait(0.1) which is the same as doing task.wait(1/10) or task.wait(6/60) it should stop waiting at the 6th frame but because 6 = 6, it waits until the frame is bigger than the frame that it should stop at. So it waits until the 7th frame to stop.

1 Like

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