Delaying a function from being called - using timer.delay() (SOLVED)

Is there anyway delaying a function to be called, I do see something called timer.delay() but after reading I do not understand, this is my first game engine so I have no experience in game development so please make the explanation clear for me, thanks in advance

1 Like

The timer.delay() function needs three things:

  1. How long the delay should be (in seconds)
  2. If the timer should run once or repeat
  3. The code to run once the timer has triggered (ie the delay has passed)
local delay = 2.5        -- 2.5 seconds
local repeated = false   -- the timer should run once

timer.delay(delay, repeated, code)

Now, the above does not show what code is. As I mentioned code should be the Lua code you wish to run when the timer triggers. When used like above it is usually called a callback function, ie a function that gets called by engine when some condition has triggered, in this case when the time has elapsed.

The callback has to be a Lua function. It can either be what is called an anonymous function or a function with a name. Like this:

-- this is a named function
local function hello()
    print("Hi there!")
end

function init(self)
    local delay = 2.5        -- 2.5 seconds
    local repeated = false   -- the timer should run once
    
    -- run the hello function once after 2.5 seconds
    timer.delay(delay, repeated, hello)

    -- alternative approach using an anonymous function:
    timer.delay(delay, repeated, function()
        print("Howdy!")
    end)
end
6 Likes

Thanks! and in your example if the hello function were to have parameters how would the code look like for

timer.delay(delay, repeated, hello)

You would need to wrap it in an anonymous function to call it with arguments:

timer.delay(delay, repeated, function()
    hello(argument)
end)
4 Likes

Yes, because timer gets as this 3rd parameter a function that is called as a callback with three parameters (self, handle, time_elapsed) by default (you don’t need to pass anything to it though, Lua will pass nil in all those places :wink: )

This mean, you can write this callback function like this:

timer.delay(delay, repeated, function(self, handle, time_elapsed)
    hello(argument)
   -- you can do here anything and access everything from script
   -- or anything assigned to this particular instance - using self
end)

As in API:

API:

For example, you can use those parameters to cancel a repeating timer after some time:

timer.delay(1, true, function(self, handle, time_elapsed)
    print("1s passed")
    if time_elapsed > 10 then
        timer.cancel(handle)
    end
end)

will be printing “1s passed” every second for 10s and than will stop this timer :wink:

4 Likes

Thanks yall

1 Like