试图取消计时器

时间:2016-09-01 05:11:40

标签: timer lua corona

我试图取消定时器,但它没有被取消,每次触摸事件发生时,都会添加一个新的定时器:

local fireTimer

local function onTouch( event )

  if( event.phase == "began") then
    fireTimer = timer.performWithDelay( 3000, fire, 0 ) <-- works fine

  elseif( event.phase == "ended" ) then
    timer.cancel( fireTimer ) <-- doesn't work, it keeps going, "pause" doesn't work either

  end
end

player:addEventListener( "touch", onTouch )  

1 个答案:

答案 0 :(得分:1)

这是因为您的触摸事件确实已经结束了#34;在火灾开始之前,因此不会取消该功能:

当延迟仅为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 )