Timer Module Accuracy Issue

i am currently having an issue with a small timer module that i’ve made.
it is functional, but when i print the time in the output, the time printed is slightly inaccurate.
how could i go about maximizing the accuracy of the timer?

timer module:

local Timer = {}
Timer.__index = Timer

function Timer.new(duration, callback)
	local self = setmetatable({}, Timer)
	self.duration = duration
	self.remainingTime = duration
	self.callback = callback
	self.running = false
	self.paused = false
	self.callbackExecuted = false
	return self
end

function Timer:start()
	if not self.running and not self.paused then
		self.startTime = os.clock()
		self.running = true
	end
end

function Timer:update()
	if self.running and not self.paused and not self.callbackExecuted then
		local currentTime = os.clock()
		self.remainingTime = math.max(0, self.duration - (currentTime - self.startTime))

		if self.remainingTime == 0 then
			self.callbackExecuted = true
			if self.callback then
				self.callback()
			end
			self:pause() -- pause timer after executing the callback
		end
	end
end

function Timer:stop()
	if self.running then
		self.running = false
		local elapsed = self.duration - self.remainingTime
		self.remainingTime = self.duration
		return elapsed
	else
		return 0
	end
end

function Timer:reset()
	self.startTime = 0
	self.remainingTime = self.duration
	self.running = false
	self.paused = false
	self.callbackExecuted = false
end

function Timer:pause()
	self.paused = true
end

function Timer:unpause()
	self.paused = false
end

return Timer

how i am using it:

local Timer = require(script.timer)

local timer = Timer.new(8, function()
	print("timer reached 0!")
end)

timer:start()

while timer.running do
	timer:update()
	task.wait(1)
	print("remaining time: " .. timer.remainingTime .. " seconds")

	if timer.remainingTime == 0 then
		break
	end
end

Line 25 of the module script all you have to do is math.floor the remaining time.

self.remainingTime = math.floor(math.max(0, self.duration - (currentTime - self.startTime)))
2 Likes

it worked, thank you

char limit, ignore

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