How to create a delay

6,447pages on
this wiki
Add New Page
Add New Page Comments0


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")
    delayFor = DELAY

function MyExample.UpdateProcessed(elapsed)
    delayFor = delayFor - elapsed
    if (delayFor <= 0) then
        UnregisterEventHandler(SystemData.Events.UPDATE_PROCESSED, "MyExample.UpdateProcessed")
        delayFor = nil


function MyExample.DoSomethingDelayed()
    -- do something usefull


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.

Also on Fandom

Random Wiki