• CoronaSDK著名API精解:timer.performWithDelay


    1 函数介绍

    简单来说就是延迟一段事件后调用某个函数。就仿佛是创建一个定时炸弹,设定爆炸时间,只是到了时间不是爆炸而是执行目标函数。

    这个函数会创建并返回一个timer对象(句柄),用来给其他的timer.xxxx函数使用。例如把这个timer对象(句柄)传递给timer.cancel()函数,用来解除之前指定的目标函数的调用。

    2 语法

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

    delay:Number类型,延迟的毫秒数,例如:1000=1秒

    listener:Listener类型,延时到期时调用的监听函数。这也可以是一个funtion listener,也可以是一个table listener。如果是table listener,它就必须有一个timer方法,因为timer事件只会发送给这个监听函数。

    iterations:(可选)指定监听函数被调用的次数。默认是1,传入0或-1表示你希望定时器永远运行下去。

    3 举例

    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 )

    重复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 )

    为Timer监听器传入额外参数:(这里借助tm实际上在监听函数里可以通过event.source来获得的方式,把外部参数传递给事件监听函数)

    -- 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" }
  • 相关阅读:
    python——时间与时间戳之间的转换
    Python3中正则模块re.compile、re.match及re.search
    javascript 模块化开发
    Python细说 xrange 和 range 的区别
    PyInstaller 生成exe文件
    win10安装mysql5.7.14winx64遇到服务无法启动问题解决方法
    Python 自定义队列 数据结构
    spring事务使用心得
    LS 存取文件
    Single Instance Application
  • 原文地址:https://www.cnblogs.com/leezj/p/4238059.html
Copyright © 2020-2023  润新知