timer.performWithDelay()

Type Function
Library timer.*
Return value Object
Revision Current Public Release (2015.2646)
Keywords timer, delay, performWithDelay
See also timer
timer.cancel()

Overview

Call a specified function after a delay. This function returns an object that can be used with other timer.* functions. For example, the returned handle could be passed to timer.cancel() to cancel the invocation of the specified listener.

Syntax

timer.performWithDelay( delay, listener [, iterations] )
delay (required)

Number. The delay in milliseconds, for example, 1000 = 1 second. Note that timers cannot execute faster than the runtime framerate of the app. For example, if the framerate of the app is 60 frames per second, as defined in the config.lua file (guide), the shortest delay for a timer is approximately 16.667 milliseconds (1000/60 = ~16.667).

listener (required)

Listener. The listener to invoke after the delay. This may be either a function listener or a table listener. If a table listener, it must have a timer method because timer events are sent to the listener.

iterations (optional)

Number. Optionally specifies the number of times listener is to be invoked. By default, it is 1; pass 0 or -1 if you want the timer to loop forever.

Examples

Function Listener
local function listener( event )
    print( "listener called" )
end

timer.performWithDelay( 1000, listener )
Table Listener
local listener = {}
function listener:timer( event )
    print( "listener called" )
end

timer.performWithDelay( 1000, listener )
Passing Parameters (1)
-- Lua closure method

local function spawnBall( randomPosition )
    ballPosition = display.newCircle( 100, 100, 20 )
    ballPosition.x = randomPosition
end

-- Obtain a random number for the spawned object's x position
local randomPosition = 100 + math.random(200)

-- Wrap "spawnBall" and "randomPosition" inside a closure
local myClosure = function() return spawnBall( randomPosition ) end
timer.performWithDelay( 2000, myClosure, 1 )
Passing Parameters (2)
-- Variable handle method

local function onTimer( event )
    -- Access "params" table by pointing to "event.source" (the timer handle)
    local params = event.source.params
    print( params.myParam1 )
    print( params.myParam2 )
end

-- Assign the timer to a variable "tm"
local tm = timer.performWithDelay( 1000, onTimer )
-- Assign a table of parameters to the "tm" handle
tm.params = { myParam1 = "Parameter1", myParam2 = "Parameter2" }