Recap - Simple Timer
Part of the Logic & Flow section of Coddy's GO journey — lesson 65 of 68.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a countdown timer application that uses time.NewTicker to count down from a specified duration to zero, displaying progress messages at regular intervals. This challenge will test your ability to combine tickers, loops, and duration calculations to create a functional timing application.
You will receive two inputs:
- A string containing the countdown duration in the format
"value:unit"(e.g.,"10:Second"or"3:Minute") - A string containing the update interval in the format
"value:unit"(e.g.,"1:Second")
Your task is to:
- Parse the first input by splitting on colons to extract the countdown duration value and unit
- Parse the second input by splitting on colons to extract the update interval value and unit
- Convert the string values to integers using the
strconvpackage - Create
time.Durationobjects for both the countdown duration and update interval using the appropriate constants:- For
"Second": multiply bytime.Second - For
"Minute": multiply bytime.Minute - For
"Hour": multiply bytime.Hour
- For
- Display the timer header:
"=== COUNTDOWN TIMER ===" - Display the timer setup:
"Starting countdown from [countdown_duration_object]" - Display the update frequency:
"Updates every [update_interval_object]" - Create a ticker using
time.NewTickerwith the update interval duration - Initialize a remaining time variable with the countdown duration
- Use a loop to count down:
- Wait for each ticker event using
<-ticker.C - Subtract the update interval from the remaining time
- If remaining time is greater than 0, display:
"Time remaining: [remaining_time_object]" - If remaining time is 0 or less, display:
"Time's up!"and exit the loop
- Wait for each ticker event using
- Stop the ticker using
ticker.Stop() - Display completion statistics:
"=== TIMER COMPLETE ===""Original duration: [countdown_duration_object]""Update interval: [update_interval_object]""Total updates displayed: [number_of_updates]"(calculate how many times the remaining time was displayed)
- Display the completion message:
"Countdown timer finished successfully"
Use the time package for ticker and duration operations, the strings package to split input strings, the strconv package to convert strings to integers, and the fmt package for output. Remember that time.NewTicker returns a ticker that sends values on its channel at regular intervals, and you must call ticker.Stop() when you're done to free up resources. This challenge demonstrates how to create a practical countdown timer using Go's timing mechanisms.
Try it yourself
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
func main() {
// Read input
var countdownInput string
var intervalInput string
fmt.Scanln(&countdownInput)
fmt.Scanln(&intervalInput)
// Parse countdown duration input
countdownParts := strings.Split(countdownInput, ":")
countdownValue, _ := strconv.Atoi(countdownParts[0])
countdownUnit := countdownParts[1]
// Parse update interval input
intervalParts := strings.Split(intervalInput, ":")
intervalValue, _ := strconv.Atoi(intervalParts[0])
intervalUnit := intervalParts[1]
// TODO: Write your code below
// Convert to time.Duration objects using switch statements
// Create the countdown timer (simulate without actual delays for testing)
// Implement the countdown loop
// Display all required messages and statistics
// Note: For testing purposes, simulate the ticker behavior without real time delays
}All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task7Error Handling In-Depth
Custom Error TypesWrapping Errors with `%w`Unwrapping with `errors.Is`Unwrapping with `errors.As`Understanding `panic`Using `recover`Recap - Safe Division10Working with Time
Getting the Current TimeCreating a Specific TimeFormatting TimeParsing Time StringsTime DurationTime ArithmeticSleeping and TickersRecap - Simple Timer2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors