Part 3: Countdown
Another common way use the timer components is to create a countdown. There are lots of different UIs for this, but to keep it as simple as possible we’ll be working with just minutes and seconds. If you remix this project, you can add in hours or days too!
Click here to remix the “Tempus” app
Components
There are two TextInputs at the top of the screen, separated by a label.
Underneath this is the main output label, which shows how much time is left in the countdown.
Finally, there’s a colour changing start/stop button which starts and resets the countdown.
Variables
The first couple of blocks we need are variables to keep track of:
- How much time is left in the countdown, called
countdown
- Whether or not the countdown is running, called
isCounting
Start the countdown
When the start button is pressed, the minutes are converted to seconds, and added to the rest of the seconds.
After that, it’s just a matter of creating a simple toggle button
Update the Label
Finally we want to show the number of minutes and seconds remaining.
Each time the timer fires, we subtract 1 from our countdown
variable and do a little bit of math to convert all the seconds back in to minutes : seconds
format.
The ternary statement is used to append a leading 0 if the number of seconds is less that 10, so the user sees 1:09
rather that 1:9
which looks a bit off putting
Your turn
If you want to use this app as a reference then you can create your own copy by clicking on the link below