类型 函数 库 timer.* 返回值 表 修订 发行版 2024.3703 关键字 timer、延迟、performWithDelay 另请参阅 timer timer.pause() timer.cancel()
在延迟之后调用指定的函数。此函数返回一个 表,该表可与其他 timer 函数一起使用。例如,返回的表可以传递给 timer.cancel() 以取消对指定侦听器的调用。
当应用程序暂停时,定时器将自动暂停,在应用程序恢复时恢复。但是,为了避免不必要的行为,强烈建议手动处理定时器。因此,如果你有正在运行的未暂停和未恢复(在代码中)的定时器,则应该通过对所有适用的定时器调用 timer.pause() 和 timer.resume() 来处理此任务。
在更改场景时,定时器不会自动取消。因此,如果你有正在运行的未取消的定时器,则必须通过对所有适用的定时器调用 timer.cancel() 来手动处理此操作。
timer.performWithDelay( delay, listener [, iterations] [, tag] )
数字. 延迟(以毫秒为单位),例如 1000
= 1 秒。请注意,定时器执行的速度不能超过应用程序的运行时帧速率。例如,如果应用程序的帧速率是 60
帧/秒,如在 config.lua
文件中定义(指南),则定时器的最短延迟大约是 16.667
毫秒1000
/60
= ~16.667
)
侦听器. 延迟后调用的侦听器。这可能是函数侦听器或表侦听器。如果是表侦听器,则它必须有 timer 方法,因为定时器事件发送到侦听器。
数字. 可选择指定 侦听器
被调用的次数。默认为 1
;如果你希望定时器无限循环,则传递 0
或 -1
。
字符串. 可选择将 标签
分配给定时器。你可以使用单个函数调用暂停、恢复或取消所有与同一 标签
共享的定时器。注意:使用 标签
需要 Solar2D 2020.3611
或更高版本。
local function listener( event ) print( "listener called" ) end timer.performWithDelay( 1000, listener )
local listener = {} function listener:timer( event ) print( "listener called" ) end timer.performWithDelay( 1000, listener )
-- 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 )
-- 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" }
如果你想添加新功能或修改现有功能,则可以从 GitHub 下载或 fork 源代码并包含在你的项目中(请参阅 使用外部模块)。