尝试取消一个定时器

我正在尝试取消一个定时器,但它在应该被取消的时候没有被取消,并且每次触摸事件发生时,都会添加一个新的定时器:

local fireTimer

local function onTouch( event )

  if( event.phase == "began") then
    fireTimer = timer.performWithDelay( 3000, fire, 0 ) <-- 正常工作

  elseif( event.phase == "ended" ) then
    timer.cancel( fireTimer ) <-- 不起作用,它仍在继续,“暂停”也不起作用

  end
end

player:addEventListener( "touch", onTouch )
点赞
用户3041972
用户3041972

这是因为当触摸事件结束后,火焰射出函数已经启动了,因此无法取消该函数:

请参考以下示例,当延迟时间仅为1时,它可以正常运行,而不是3000。

local player = display.newRect(0, 0, 150, 50)

local function fire()
    print("touched")
end

local function fireTimer2()
    print("Ended touched")
end

local function onTouch(event)

    if (event.phase == "began") then
        fireTimer = timer.performWithDelay(1, fire, 0)

    elseif (event.phase == "ended") then
        timer.cancel(fireTimer)
        print("Ended touched")
    end
end

player:addEventListener("touch", onTouch)
2016-09-02 05:52:31