如何在有限时间内运行函数?

我有一个函数,希望在3秒内每2秒调用一次。

我尝试使用timer.performwithDelay(),但它没有回答我的问题。

以下是我想在3秒内每2秒调用的函数:

function FuelManage(event)
    if lives > 0 and pressed==true then

        lifeBar[lives].isVisible=false
        lives = lives - 1
--      print( lifeBar[lives].x )
        livesValue.text = string.format("%d", lives)

    end
end

如何使用timer.performwithDelay(2000, callback, 1)调用我的函数FuelManage(event)

点赞
用户2895078
用户2895078

可以像这样在定时器内部设置定时器:

function FuelManage(event)
    if lives > 0 and pressed == true then
        lifeBar[lives].isVisible = false
        lives = lives - 1
--      print( lifeBar[lives].x )
        livesValue.text = string.format("%d", lives)
    end
end

-- 主定时器,每2秒调用一次
timer.performWithDelay(2000, function()
    -- 子定时器,每秒钟调用一次,共3秒
    timer.performWithDelay(1000, FuelManage, 3)
end, 1)

不过需要注意,目前这种设置方式会导致无限数量的定时器在运行... 因为第一个定时器的生命周期低于第二个定时器。所以你可能需要想些如何确保在再次调用第二个定时器之前先取消它的方法,这种事情。

2014-04-27 11:35:13
用户869951
用户869951

看起来你实际上想要从 "现在" 开始检查一些内容,持续 3 秒钟。你可以安排注册和注销 enterFrame 事件。使用它将在感兴趣的时间段内每个时间步长调用你的 FuelManage 函数:

    function cancelCheckFuel(event)
        Runtime:removeListener('enterFrame', FuelManager)
    end

    function FuelManage(event)
        if lives > 0 and pressed==true then
            lifeBar[lives].isVisible=false
            lives = lives - 1
            -- print( lifeBar[lives].x )
            livesValue.text = string.format("%d", lives)
        end
    end

    -- fuel management:
    local startFuelCheckMS = 2000    -- start checking for fuel in 2 seconds
    local fuelCheckDurationMS = 3000 -- check for 3 seconds
    local stopFuelCheckMS = startFuelCheckMS + fuelCheckDurationMS
    timer.performWithDelay(
        startFuelCheckMS,
        function() Runtime:addEventListener('enterFrame', FuelManager) end,
        1)
    timer.performWithDelay(
        stopFuelCheckMS,
        function() Runtime:removeEventListener('enterFrame', FuelManager) end,
        1)

如果这个频率太高,那么你将需要使用计时器,并跟踪时间:

    local fuelCheckDurationMS = 3000 -- check for 3 seconds
    local timeBetweenChecksMS = 200 -- check every 200 ms
    local totalCheckTimeMS = 0
    local startedChecking = false

    function FuelManage(event)
        if lives > 0 and pressed==true then
            lifeBar[lives].isVisible=false
            lives = lives - 1
            -- print( lifeBar[lives].x )
            livesValue.text = string.format("%d", lives)
        end

        if totalCheckTimeMS < 3000 then
            -- check again in timeBetweenChecksMS milliseconds
            timer.performWithDelay(timeBetweenChecksMS, FuelManage, 1)
            if startedChecking then
                totalCheckTimeMS = totalCheckTimeMS + timeBetweenChecksMS
            end
            startedChecking = true
        end
    end

    -- fuel management:
    local startFuelCheckMS = 2000    -- start checking for fuel in 2 seconds
    timer.performWithDelay(startFuelCheckMS, FuelManage, 1)
2014-04-27 20:32:50