Using a function that can be called at a later time can be helpful when organizing the timing of your game objects' appearance in an application. The timer library will allow us to handle our functions in a timely manner.
The timer function enables you to trigger events at a specific delay (in milliseconds) of your choosing.
timer.performWithDelay(delay, listener [, iterations])
: This invokes the listener after a delay in milliseconds and returns a handle to an object that you can pass to timer.cancel()
in order to cancel the timer before it invokes the listener. For example:local function myEvent() print( "myEvent called" ) end timer.performWithDelay( 1000, myEvent )
timer.cancel(timerId)
: This cancels a timer operation initiated with timer.performWithDelay()
. The parameter is as follows:timerId
: This is an object handle returned by the call to timer.performWithDelay()
. For example:local count = 0 local function myEvent() count = count + 1 print( count ) if count >= 3 then timer.cancel( myTimerID ) -- Cancels myTimerID end end
timer.pause(timerId)
: This pauses a timer object started with timer.performWithDelay()
. The parameter is:timer.resume(timerId)
: This resumes a timer that was paused with timer.pause(timerId)
. The parameter is as follows:timerID
: This the timer ID from timer.performWithDelay()
. For example:local function myEvent() print( "myEvent called" ) end myTimerID = timer.performWithDelay( 3000, myEvent ) -- wait 3 seconds result = timer.pause( myTimerID ) -- Pauses myTimerID print( "Time paused at " .. result ) result = timer.resume( myTimerID ) -- Resumes myTimerID print( "Time resumed at " .. result )