Hello all,
I’ll be releasing a Timer module I’ve worked on.
This module was originally intended to be used for my game, but this has some uses so I decided to release it publicly. It’s meant to easily manage timers, as well as their current states. You can easily pause, kill, resume and play a timer with this.
Usecases
The main functionality the timer module offers you is:
- Accurate delay
- Detailed information about the timer
With this module, it’s especially easy to check for instance how much time the timer that’s running has left. Take this code for example:
local MyTimer = Timer.new(5)
MyTimer:Start()
wait(1)
print(MyTimer:GetRemaining()) -- Approximately 4 seconds.
print(MyTimer:GetState()) -- Running
Not only does it tell you how much time the timer has left, but also what state it is currently in.
If you get the state of that timer after 5 seconds had passed, it would return Dead
.
What’s especially useful is that you can set callbacks for different states - you can set a callback for when the timer starts running, for when it finishes, when it dies, or when it gets stopped (with the :Stop()
method).
This module is greatly optimized by using a sorted array.
It sorts all timers in the queue by their remaining time left, the one with the least time left being at the end of the array. A newly created timer is inserted into the queue through a binary search algorithm.
It only updates the remaining time left of the last timer in the queue, and when that timer dies it goes on to the next one.
The documentation has a lot more to say about this than I do
Documentation
Example usage
local Timer = require(script.Parent.TimerModule)
local MyTimer = Timer.new(5) -- creates a timer with a 5 second lifespan
MyTimer:OnStopped(warn) -- warns when the timer stops
print(MyTimer:GetLength()) -- 5
print(MyTimer:GetState()) -- Paused
MyTimer:Start()
print(MyTimer:IsRunning()) -- true
wait(1)
print(MyTimer:GetRemaining()) -- approx. 4 seconds