C_Timer provides three functions to trigger a callback function after a given duration
- After() starts a simple timer that calls 'callback' after 'duration' seconds
- NewTimer() also returns a handle that responds to handle:Cancel()
- NewTicker() also repeats for the specified number of iterations (or indefinitely)
C_Timer.After(duration, callback) C_Timer.NewTimer(duration, callback) -- cancellable C_Timer.NewTicker(duration, callback[, iterations]) -- cancellable, repeating
- Number - Seconds before the timer completes
- Function - What you want to execute when the timer's duration has elapsed
- Number - (NewTicker only) Number of times to repeat, or indefinite if omitted
The following example illustrates the utility of each function
local function myFunc() -- do something end -- call myFunc() in 1 sec C_Timer.After(1, myFunc) -- call myFunc() in 5 sec, but cancel it right away local myTimer = C_Timer.NewTimer(5, myFunc) myTimer:Cancel() -- call myFunc() every 0.1 sec, ten times, but cancel it right away local myTicker = C_Timer.NewTicker(0.1, myFunc, 10) myTicker:Cancel()
It is also possible to create a function that calls itself iteratively using only C_Timer.After
local myFunc function myFunc() -- do something C_Timer.After(1, myFunc) -- repeat in 1 sec end
Timers and Tickers also respond to handle:IsCancelled()
local myTimer = C_Timer.NewTimer(5, myFunc) print(myTimer:IsCancelled()) -- prints "false" myTimer:Cancel() print(myTimer:IsCancelled()) -- prints "true"
- Timing accuracy is limited to the frame rate
- Duration greater than 0.001 (1ms) will not trigger until at least the next frame
- Duration less than 0.001 (1ms) trigger may trigger during the current frame and could slow the client
- Duration of exactly zero may cause an error if looping indefinitely
- After() is more efficient than the other two if the added features are not required
[Sticky] 6.0 Add-On Changes | 2014-09-09 16:54 | Rygarius
C_Timer [is] cheaper than using an Animation or OnUpdate [which] have overhead that applies every [frame]. For OnUpdate, the overhead lies in the extra function call to Lua. For Animations, we’re doing work C-side that allows us to support smoothing, parallel animations, and animation propagation. In contrast, the new C_Timer system uses a standard heap implementation. It’s only doing work when the timer is created or destroyed (and even then, that work is fairly minimal).
The one case where you’re better off not using the new C_Timer system is when you have a ticker with a very short period – something that’s going to fire every couple frames. For example, you have a ticker you want to fire every 0.05 seconds; you’re going to be best served by using an OnUpdate function (where about half the function calls will do something useful and half will just decrement the timer).
- Patch 7.3.5 (2018-01-16): NewTimer() and NewTicker() also respond to handle:IsCancelled().
- Patch 6.0.2 (2014-10-14): After(), NewTimer() and NewTicker() added.