Corona SDK and other Game Development Tutorials
@gamebuilding

Creating a Timer with Corona SDK

In today’s post, we are covering another very simple topic, but one that’s essential to game development: a game timer. Some games will only allow 60 seconds to complete a level or a set amount of time to achieve a goal. So, here’s how you can create a timer with Corona SDK.

display.setStatusBar(display.HiddenStatusBar) _W = display.contentWidth _H = display.contentHeight number = 0

local txt_counter = display.newText( number, 0, 0, native.systemFont, 50 )
txt_counter.x = _W/2
txt_counter.y = _H/2
txt_counter:setTextColor( 255, 255, 255 )
function fn_counter()
number = number + 1
txt_counter.text = number
end
timer.performWithDelay(1000, fn_counter, 0)

Most of the code should be pretty self explanatory, but the code above is using a timer to add 1 to the counter in the middle of the screen. If you have questions or comments, please leave them below!

Download Source Code

4 Comments
  1. Is there a way to cancel timer?

    Like…if we have a timer running, and we stop it, so that the function doesn’t get called.

    I’m looking at Corona API, but there is barely any info on timer.cancel.

    It mentions some “timerID”, but it doesn’t explain much about it.

    • You should declare a variable to receive this ID, like this:

      myTimerVariable = timer.performWithDelay(1000, fn_counter, 0)

      Then, when you want to cancel, just do this:

      timer.cancel(myTimerVariable)

  2. How do I pause this timer?

  3. Dude if you ant to stop timer put your all codes in one function method.

    local function timerClock()

    local txt_counter = display.newText( number, 0, 0, native.systemFont, 50 )
    txt_counter.x = _W/2
    txt_counter.y = _H/2
    txt_counter:setTextColor( 255, 255, 255 )
    function fn_counter()
    number = number + 1
    txt_counter.text = number
    end
    local clock = timer.performWithDelay(1000, fn_counter, 0)

    end

    timerClock()– to start timer

    timer.Cancel(clock)

Leave a Reply