I have a lib named Scorpio, it has a task schedule system works like:
Lua Code:
Scorpio "TestAddon" "1.0.0"
-- __Async__ is used to wrap the target function, so when the
-- function is called, it'd be processed in a coroutine, the coroutine
-- will be recycled when the target function finished its job
__Async__()
function LoopJob()
while true do
NextEvent("PLAYER_REGEN_DISABLED") -- wait the event
print("Start combat")
local cnt = 0
repeat
Delay(1) -- delay for 1 sec
cnt = cnt + 1
print("[Combat]", cnt)
until not InCombatLockdown()
print("End combat")
end
end
-- Start the loop
LoopJob()
With the system, we can avoid the callback hell and keep any logic in one function. And the better part of the system is if we put all hard works to it, it really can smooth the function calls(delay the call if there is too much operations in one phase) and make the fps no dropping.
So, if you are interesting, you can find the lib at
https://github.com/kurapica/Scorpio, it's also uploaded to the curseforge.
For your example, you may check the Next and Continue API provided by the Scoprio, the Next is used to delay the process to the next phase, the Continue is used to check if there is enough time in the current phase to continue the process, otherwise, it'd delay it to the next phase.