timer.cancel()

Type Function
Library timer.*
Revision Release 2024.3703
Keywords timer, delay, cancel
See also timer.performWithDelay()

Overview

Cancels a specific timer or all timers with the same tag that were initiated with timer.performWithDelay().

Syntax

timer.cancel( whatToCancel )
whatToCancel (required)

Object or String. The timer ID from, or tag passed to, timer.performWithDelay(). Note: Using tag requires Solar2D 2020.3611 or a newer build.

Example

local function listener( event )
    print( "listener called" )
end
 
timer1 = timer.performWithDelay( 2000, listener )  -- wait 2 seconds

-- sometime later...
timer.cancel( timer1 )
local function listener( event )
    print( "listener called" )
end
 
timer1 = timer.performWithDelay( 2000, listener, "red" )  -- wait 2 seconds
timer2 = timer.performWithDelay( 3000, listener, "blue" )  -- wait 3 seconds

-- sometime later...
timer.cancel( "red" )
local t = {}
function t:timer( event )
    local count = event.count
    print( "Table listener called " .. count .. " time(s)" )
    if count >= 3 then
        timer.cancel( event.source ) -- after 3rd invocation, cancel timer
    end
end
 
-- Register to call t's timer method an infinite number of times
timer.performWithDelay( 1000, t, 0 )