Rust Program to Create a Countdown Timer


Countdown Timer

Rust Programming Language


Countdown Timer


Problem


Rust program to create a countdown timer.

Input


use std::{thread, time};

fn main() {
    let duration = time::Duration::from_secs(60); // 1 minute countdown
    let mut remaining_time = duration.as_secs() as i32;

    while remaining_time > 0 {
        print!("{} ", remaining_time);
        std::io::stdout().flush().unwrap();
        thread::sleep(time::Duration::from_secs(1));
        remaining_time -= 1;
    }

    println!("Time's up!");
}{codeBox}

Output


60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Time's up!{codeBox}

Explanation


In this program, we use the std::thread and std::time modules to create a countdown timer. We start by setting the duration of the countdown to 1 minute using the time::Duration struct.

We then create a loop that will run until the remaining time is zero. In each iteration of the loop, we print the remaining time to the console using print!, flush the output to make sure it's immediately visible using std::io::stdout().flush().unwrap(), wait for one second using thread::sleep, and then subtract one second from the remaining time.

Once the loop is done, we print "Time's up!" to let the user know that the countdown has finished.

You can adjust the duration of the countdown by changing the value passed to time::Duration::from_secs.




Post a Comment