Front-End: Developing a Timer

In my last post, I talked about using a button action to access text input from a text box. This could then be added to a table or saved to a database, or both in my case. For this post, I will discuss how to build a timer for an app.

Other people have already solved this problem, so I found an awesome tutorial ( from corona labs.

This tutorial was easy to follow, the code was clear to understand, it runs quickly, and it works. Everything you want in a tutorial. Here’s my final snippet of code for a functional timer that sits in the top left corner of the screen. I put this code in the “DID” section of the scene creation management within composer so that the timer wouldn’t start until the scene was loaded and on screen. The mui functions come from the Material-UI library which I am using to help me design my user experience (

elseif ( phase == “did” ) then

local secondsLeft = 3 * 60

local clockText = display.newText(

clockText:setFillColor( 1,1,1,1 )
sceneGroup:insert( clockText )
local function updateTime()

secondsLeft = secondsLeft – 1

if secondsLeft <= 0 then

–print(“Time is up!”) –run function that ends the level/scene
–for x,y in pairs(responsesTable) do
— print(x,y)
— time is tracked in seconds. We need to convert it to minutes and seconds

local minutes = math.floor( secondsLeft / 60 )
local seconds = secondsLeft % 60
— make it a string using string format.
local timeDisplay = string.format( “%02d:%02d”, minutes, seconds )
clockText.text = timeDisplay

— run the timer

local countDownTimer = timer.performWithDelay( 1000, updateTime, secondsLeft )

Next post I’ll discuss input/output, pulling text from a file, and using the system resource directory.


EDIT: I changed if seconds == 0 to if seconds <= 0 just in case a problem makes the program skip 0.

1 Comment

  1. Looking good. At first, the formatting on this post threw me off. I was wondering why you subtracted 3minutes from 3*60, then I realized that must be a comment in your lua file.

    One thing I might do to be safe is to change if secondsLeft == 0 to <= 0. That way, if you somehow have an error and don't end at 0 exactly, you still have the timer stop.

Leave a Comment

Your email address will not be published. Required fields are marked *