sriyanto

Timer

Oct 11th, 2022
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.24 KB | None | 0 0
  1. local Timer = {}
  2. Timer.__index = Timer
  3.  
  4. function Timer.new()
  5.     local self = setmetatable({}, Timer)
  6.  
  7.     self._finishedEvent = Instance.new("BindableEvent")
  8.     self.finished = self._finishedEvent.Event
  9.    
  10.     self._running = false
  11.     self._startTime = nil
  12.     self._duration = nil
  13.    
  14.     return self
  15. end
  16.  
  17. function Timer:start(duration)
  18.     if not self._running then
  19.         local timerThread = coroutine.wrap(function()
  20.             self._running = true
  21.             self._duration = duration
  22.             self._startTime = tick()
  23.             while self._running and tick() - self._startTime < duration do
  24.                 wait()
  25.             end
  26.             local completed = self._running
  27.             self._running = false
  28.             self._startTime = nil
  29.             self._duration = nil
  30.             self._finishedEvent:Fire(completed)
  31.         end)
  32.         timerThread()
  33.     else
  34.         warn("Warning: timer could not start again as it is already running.")
  35.     end
  36. end
  37.  
  38. function Timer:getTimeLeft()
  39.     if self._running then
  40.         local now = tick()
  41.         local timeLeft = self._startTime + self._duration - now
  42.         if timeLeft < 0 then
  43.             timeLeft = 0
  44.         end
  45.         return timeLeft
  46.     else
  47.         warn("Warning: could not get remaining time, timer is not running.")
  48.     end
  49. end
  50.  
  51. function Timer:isRunning()
  52.     return self._running
  53. end
  54.  
  55. function Timer:stop()
  56.     self._running = false
  57. end
  58.  
  59. return Timer
Add Comment
Please, Sign In to add comment