Custom Timer Class

How could I achive making my own Timer class/object? This is what I have tried so far, but the Pause method seems to not work.

Server Script

local Timer = require(script.ModuleScript)

local t1 = Timer.Create("TimerOne",1,10)
t1:Start()

wait(1)
t1:Pause()

Timer Module


local Timer = {}
Timer.__index = Timer


function Timer.Create(name,start,stop)
	local newtimer = {}
	setmetatable(newtimer,Timer)
	
	newtimer.ClassName = "Timer"
	newtimer.Name = name
	newtimer.InitialTime = start
	newtimer.FinalTime = stop
	
	newtimer.CurrentTime = newtimer.InitialTime
	
	newtimer.isTicking = false
	newtimer.Paused = false
	
	return newtimer
end

function Timer:Destroy()

end

function Timer:Start()
	repeat
		wait(1)
		if self.Paused ~= true then
			print(self.CurrentTime)
			self.CurrentTime = self.CurrentTime + 1
		end
	until self.CurrentTime == self.FinalTime + 1
end

function Timer:Pause()
	self.Paused = true
end

function Timer:Cancel()
	
end

return Timer
1 Like

I suggest you take a look at a few resources and see how they incorporate their Timer classes as reference for your own code. It might help you develop something.

1 Like

You call Timer:Start() which runs the following code

	repeat
		wait(1)
		if self.Paused ~= true then
			print(self.CurrentTime)
			self.CurrentTime = self.CurrentTime + 1
		end
	until self.CurrentTime == self.FinalTime + 1

Timer:Pause() won’t be called until Time:Start() has finished.

To fix this, wrap your timers logic in a coroutine.

function Timer:_Run()
	repeat
		wait(1)
		if self.Paused ~= true then
			print(self.CurrentTime)
			self.CurrentTime = self.CurrentTime + 1
		end
	until self.CurrentTime == self.FinalTime + 1
end

function Timer:Start()
	local run = coroutine.wrap(Timer._Run)
	run(self)
end