API:Timers
From TheWarWiki
WAR API Help
In your .mod file, place the following:
<OnUpdate>
<CallFunction name="MyAddon.OnUpdate" />
</OnUpdate>
Then in your lua file,
MyAddon = {}
function MyAddon.OnUpdate(elapsed)
-- this will now run every frame, with elapsed being the seconds since the last time called.
end
For an example that runs every second,
MyAddon = {}
local TIME_DELAY = 1
local timeLeft = TIME_DELAY -- start in TIME_DELAY seconds
function MyAddon.OnUpdate(elapsed)
timeLeft = timeLeft - elapsed
if timeLeft > 0 then
return -- cut out early
end
timeLeft = TIME_DELAY -- reset to TIME_DELAY seconds
-- this will run roughly every second. If TIME_DELAY were 2, it'd run every 2 seconds.
end
Warning: This function is called on every frame update, which is hopefully about 20 to 40 or more times per second. Even if you are polling for changes instead of doing a time-delayed action, you should put in some code to do the polling (especially if it is time-intensive) only every so often. This code is called a "throttle" and its action is called "throttling," making sure that something, that would otherwise happen too often, doesn't.
Even better would be if there were a third party library for scheduling your function calls that need to execute every few seconds (or minutes). Having a centralized library function, even if it is user-provided, beats having many functions triggered in addons in the update.
However, with the tools provided by WAR, if you can achieve your functionality through registering for events, that will be the biggest performance gain you can give to the user (assuming the event is not triggered extremely often). So, in order of recommendation, register for an appropriate event, failing that register with a third party timer library, and if you really need to do your own code on every frame update or similar, then you can use the OnUpdate functionality for that. Just be sure to throttle!
