Nov 132011
 

Timers are one of the most useful tools a developer has at their disposal when creating an app, this is a run down on them.

Here’s an example of how a timer might be used;

1
2
3
4
local function spawnPeach (event)
local peach = display.newImage("peach.png")
end
timer.performWithDelay(3000, spawnPeach, 1)

If you put this into your code (using your own image, of course) you would see the image appear after 3 seconds. (3000 equates to 3 seconds as timers use milliseconds.)

spawnPeach is of course the name of our function, while the number 1 indicates we only want the function to happen once.

Now, there are many times you may want to cancel the timer before it is complete – to do this, we must give the timer a name. We would do so like this;

1
2
3
4
local function spawnPeach (event)
local peach = display.newImage("peach.png")
end
peachTimer = timer.performWithDelay(3000, spawnPeach, 1)

Now if we want to cancel the timer we can do with just one line of code;

1
timer.cancel(peachTimer)

You might be wondering when you would ever need to cancel a timer you had created. Well, there are many reasons but the most common seems to be when you are changing scenes using Director (or a Director alternative) and not cancelling the timer can cause errors.

In that case, when you changed scenes you would use the above line of code to cancel the timer.

BUT – what if the timer has already fired and you are trying to cancel it? Well, that will also return an error. The line below will check to see if the timer is still running it and cancel it if so;

1
if peachTimer then timer.cancel(peachTimer) end

And that’s it!

This was written to be very basic and easy for newer users to understand, however if anyone has any more advanced questions please feel free to let me know in the comments and I will answer them for you.

I hope everyone is having a great weekend!

Peach :)

This post was written for Noah aka ZomDroid.

Like this post? Subscribe to the monthly newsletter!

 

  15 Responses to “Understanding Timers”

  1. I do like a good “that’s what she said” ;)

    I think that’s awesome – one day!

    You’re very welcome – I hope my passion and enthusiasm can help fuel yours as you move forward; the Corona community is wonderful and is a constant source of energy and encouragement for me :)

  2. That’s what she said…
    But seriously, I was able to start and complete and get onto my iPad the first level of a game in one day using Corona, examples and tutorials I found on the web (yours included of course). This program deserves all the evangelizing any of us can give it (you’re certainly holding up your part). I started in Lingo and was forced on to Flash, but this Lua coding is better than both – except I do miss Shockwave 3D and Havok. At least I get my physics back! Anyway, thanks for your apparently boundless energy and dedication!

  3. Wow, lol, turn my back for two seconds and you’ve solved it! Well done; elegance is less important than functionality ;)

  4. figured out this solution anyway. probably not elegant. my logic teacher called me a meta physician:

    physics.removeBody(acorn)
    acorn.y=-1000;

  5. I added a delay to the self-destruction of the object I’m trying to stop the score from tracking after it descends past a certain point. it stops the timer at the point the object is destroyed:

    transition.to(acorn, {time = 10000, y = -acorn.contentHeight,
    onComplete = function(self) self.parent:remove(self); self = nil; end
    })

    I’ll shut up now…

  6. for the timer to keep going, the score has to keep going to the -100,000′s…

  7. oops, I removed these also: Runtime:removeEventListener(“enterFrame”, checkScore)

  8. no errors. the timer dies completely. here’s the code: I’ve commented out the stuff that killed the timer:
    function updateTime()
    timerTicks = timerTicks – 1
    timerText.text = “time: ” .. timerTicks

    if timerTicks==0 then
    physics.pause()
    end
    end

    function checkScore()
    if acorn.y>=1300 then
    score = score – 200
    –physics.removeBody(acorn)
    –acorn:removeSelf()
    –acorn = nil
    scoretext.text = tostring(score)
    Runtime:removeEventListener(“enterFrame”, checkScore)

    end
    if acorn2.y>=1300 then
    score = score – 200
    scoretext.text = tostring(score)
    –physics.removeBody(acorn2)
    –acorn2:removeSelf()
    –acorn2 = nil
    Runtime:removeEventListener(“enterFrame”, checkScore)

    end
    if acorn3.y>=1300 then
    score = score – 200
    scoretext.text = tostring(score)
    –physics.removeBody(acorn3)
    –acorn3:removeSelf()
    –acorn3 = nil
    Runtime:removeEventListener(“enterFrame”, checkScore)

    end
    –if score <=-400 then
    — physics.pause()
    –end
    end

    local function showtimer (event)
    –if event.phase == "ended" then

    – Runtime:removeEventListener ( "isShake", showtimer )

    –timerText.isVisible = true
    local timeTaken = timer.performWithDelay( 1000, updateTime, timerTicks )
    –Runtime:addEventListener("enterFrame", checkScore)
    — end
    end
    local shake = {}
    function shake:accelerometer(e)
    if(e.isShake == true) then
    physics.addBody(acorn, {bounce=.2})
    physics.addBody(acorn2, {bounce=.2})
    physics.addBody(acorn3, {bounce=.2})

    showtimer()
    –Runtime:addEventListener("enterFrame", checkScore)

    end
    end
    Runtime:addEventListener("accelerometer", shake)
    Runtime:addEventListener("enterFrame", checkScore)

  9. Hey Mike, uh – it’s hard to say without running your code, honestly. I’m also not 100% sure what “snags” means in this case; lags? Throws an error?

  10. hi Peach,
    I created a 60 second countdown timer that snags whenever I remove objects from Physics, removeSelf’s and nil them simultaneously. is there any possible excuse for this? ;-p

  11. Halp! I was hoping for something on how to change the timer length…this never seems to work for me :( ie, if i want each time after the timer fires, for it to choose a new random time length?

    • Hey Gabriel,

      You can only cancel the timer and restart it – it can’t get a random value each time if it is repeating. That said, perhaps using two timers you could rig something up? One timer going off multiples times, calling a function that has a timer that goes off once – the first timer could be used to set the random value for the second.

      Does that make any sense?

      Peach :)

  12. @Noah – You’re welcome, sorry it took so long ;)

    @Rodrigo – No worries, very glad you enjoyed it.

    Peach :)

  13. Hello Mrs. Peach!

    Thank you for this simple and GREAT tuto about the famous “timers”. I did not know that the timers would work like function`s callbacks as well. :S

    Peace & Success!

    Cheers,
    Rodrigo.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.