Skip to content

Instantly share code, notes, and snippets.

@glinesbdev
Created May 10, 2021 14:04
Show Gist options
  • Save glinesbdev/99b8fdb3416a8318f0e0945df9f9d916 to your computer and use it in GitHub Desktop.
Save glinesbdev/99b8fdb3416a8318f0e0945df9f9d916 to your computer and use it in GitHub Desktop.
Lua Timer
local Timer = {}
Timer.__index = Timer
local RunService = game:GetService("RunService")
function Timer.new()
local self = setmetatable({}, Timer)
-- Events
self._finishedEvent = Instance.new("BindableEvent")
self.Finished = self._finishedEvent.Event
self._countdownEvent = Instance.new("BindableEvent")
self.Countdown = self._countdownEvent.Event
-- Properties
self._running = false
self._duration = nil
self._time = nil
return self
end
function Timer:Start(duration)
if not self._running then
local timerThread =
coroutine.wrap(
function()
self._running = true
self._duration = duration
self._time = tick()
local prevNum = 0
while self._running and tick() - self._time < duration do
RunService.Heartbeat:Wait()
local rounded = 0
if self._running then
rounded = math.round(self:GetTimeLeft())
end
if rounded >= 0 and prevNum ~= rounded then
self._countdownEvent:Fire(rounded)
prevNum = rounded
end
end
self._running = false
self._time = nil
self._duration = nil
self._finishedEvent:Fire()
end
)
timerThread()
else
warn("Timer is already running!")
end
end
function Timer:Restart(duration)
self:Stop()
self:Start(duration)
end
function Timer:GetTimeLeft()
if self._running then
local now = tick()
local timeLeft = self._time + self._duration - now
if timeLeft <= 0 then
timeLeft = 0
end
return timeLeft
else
warn("Timer is not running. You must use timer:Start()")
end
end
function Timer:IsRunning()
return self._running
end
function Timer:Stop()
self._running = false
end
return Timer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment