local DELAY = 5 -- in seconds local delayFor function MyExample.DoSomething() if (not delayFor) then -- don't want to register it twice RegisterEventHandler(SystemData.Events.UPDATE_PROCESSED, "MyExample.UpdateProcessed") end delayFor = DELAY end function MyExample.UpdateProcessed(elapsed) delayFor = delayFor - elapsed if (delayFor <= 0) then UnregisterEventHandler(SystemData.Events.UPDATE_PROCESSED, "MyExample.UpdateProcessed") MyExample.DoSomethingDelayed() delayFor = nil end end function MyExample.DoSomethingDelayed() -- do something usefull end
The function DoSomething will call DoSomethingDelayed after a given amount of time.
This function will register the EventHandler SystemData.Events.UPDATE_PROCESSED. The function of this EventHandler get called on every client update, and will have an argument which contains the time since last update.
The function UpdateProcessed will then substract the time since last update from the time you want to wait. Once the time you want to wait reaches 0 or lower (so the time you want to wait has passed) the EventHandler get unregistered, otherwise the UpdateProcessed would be called again on the next client update, and your DelayedFunction would called again, over and over. After the EventHandler is unregistered, the function which contains the code which should processed delayed will be called, and after that, the delayFor local get set back to nil, and the next time DoSomthing get called, the delay process will start again. On a sidenote: DoSomething will always reset the delay timer, so even if you called it once, then wait 2,5s (5s until the delayed function get called) and after those 2,5s call DoSomething again, the timer will reset to 5s. If you don't want the timer to reset always you have to put the delayFor = DELAY into the if conditional.
Function original wrote by Healix. See this post.