Today, we'll create a simple but functional countdown timer, this time in C++, that can be used in various applications. We'll build it using clean, modern C++ practices and make it flexible enough to handle different time formats.

Just in time since I am tested on C++ soon

What is C++

C++ is a high-performance, general-purpose programming language that extends C by adding object-oriented programming (OOP) features. It was developed by Bjarne Stroustrup in the early 1980s. C++ supports multiple programming paradigms, including procedural, object-oriented, and generic programming, making it widely used in software development, game development, systems programming, and embedded systems.

Project Overview

A countdown timer is a common UI element used in many applications, from cooking apps to workout timers. Our implementation will:

  • Allow setting a countdown duration
  • Display time remaining in hours:minutes:seconds format
  • Support pausing and resuming
  • Provide user feedback when the countdown completes

Let's dive into the implementation!

#include <iostream>   // For input and output operations
#include <chrono>     // For time-related functions
#include <thread>     // For adding delay/sleep functionality
#include <iomanip>    // For formatting output (setfill, setw)
#include <string>     // For using the string data type

using namespace std;

// CountdownTimer class
class CountdownTimer {
private:
    int hours;      // Stores hours for the timer
    int minutes;    // Stores minutes for the timer
    int seconds;    // Stores seconds for the timer
    bool is_running; // Flag to track if the timer is running
    bool is_paused;  // Flag to track if the timer is paused

    // Helper function to format time as HH:MM:SS
    string formatTime() const {
        // setw(2) ensures two-digit formatting (e.g., 01 instead of 1)
        cout << setfill('0') << setw(2) << hours << ":";
        cout << setfill('0') << setw(2) << minutes << ":";
        cout << setfill('0') << setw(2) << seconds;

        // Function signature requires returning a string, but it's missing
        return "";  // Returning an empty string (fix needed)
    }

    // Update timer values (decreases time by one second)
    void updateTimer() {
        if (seconds > 0) {
            seconds--;  // Decrease seconds
        } else if (minutes > 0) {
            minutes--;  // Borrow from minutes
            seconds = 59;
        } else if (hours > 0) {
            hours--;    // Borrow from hours
            minutes = 59;
            seconds = 59;
        }
    }

public:
    // Constructor to initialize timer with given hours, minutes, and seconds
    CountdownTimer(int h = 0, int m = 0, int s = 0)
        : hours(h), minutes(m), seconds(s), is_running(false), is_paused(false) {

        // Normalize time values to ensure valid input
        minutes += seconds / 60;  // Convert excess seconds into minutes
        seconds %= 60;            // Keep seconds within 0-59 range
        hours += minutes / 60;    // Convert excess minutes into hours
        minutes %= 60;            // Keep minutes within 0-59 range
    }

    // Function to start the countdown
    void start() {
        is_running = true;
        is_paused = false;

        // Continue looping until the timer reaches zero
        while (is_running && (hours > 0 || minutes > 0 || seconds > 0)) {
            if (!is_paused) {
                // \r moves the cursor to the beginning of the line (overwrites text)
                cout << "\r" << formatTime() << flush;

                this_thread::sleep_for(chrono::seconds(1));  // Wait for 1 second
                updateTimer();  // Decrease time
            }
        }

        // When time is up, display final message
        if (hours == 0 && minutes == 0 && seconds == 0) {
            cout << "\r" << formatTime() << " - Time's up!" << endl;
        }
    }

    // Function to pause the timer
    void pause() {
        is_paused = true;
    }

    // Function to resume the timer
    void resume() {
        is_paused = false;
    }

    // Function to stop the timer completely
    void stop() {
        is_running = false;
    }

    // Function to check if the timer is running
    bool isRunning() const {
        return is_running;
    }

    // Function to check if the timer is paused
    bool isPaused() const {
        return is_paused;
    }
};

// Main function: Entry point of the program
int main() {
    cout << "Countdown Timer Demo\n";
    cout << "Setting timer for 1 minute and 30 seconds...\n";

    // Creating an object of CountdownTimer with 1 minute 30 seconds
    CountdownTimer timer(0, 1, 30);  
    timer.start();  // Start the countdown

    return 0;  // Return 0 to indicate successful execution
}

Key Features Explained

  • Time Formatting

The timer uses a helper function formatTime() to display the time in a clean HH:MM:SS format. It uses setfill and setw to ensure consistent two-digit display for each unit.

  • Timer Logic

chrono for accurate time measurement

this_thread::sleep_for() for the countdown delay

A normalized time representation that handles
overflow correctly

  • State Management

Running, Paused, Stopped

  • User Interface

Real-time updates using carriage return (\r)

Clear visual feedback

A completion message when the countdown ends

Usage Example

// Create a timer for 2 hours, 30 minutes, and 15 seconds
CountdownTimer timer(2, 30, 15);

// Start the countdown
timer.start();

// You can pause/resume as needed
timer.pause();
timer.resume();

// Stop the timer early if needed
timer.stop();

Potential Enhancements

The current implementation could be extended with:

  • Sound alerts when the timer completes
  • Custom display formats
  • Multiple concurrent timers
  • Save/load timer presets
  • A GUI interface

Conclusion

This countdown timer implementation provides a solid foundation for timing functionality in C++ applications. It's thread-safe, easy to use, and can be extended to meet specific needs.

The complete source code is available in the artifact above. Feel free to modify and enhance it for your own projects!

Author Of article : Johnny Santamaria Read full article