简体   繁体   中英

How to countdown in seconds from minutes using a countdown timer

Currently developing a simple windows phone 8.1 silverlight app with an implemented countdown time. I have it working where I can input a set amount of minutes and it countdowns fine but what I am wanting to happen is for a user to input an amount of minutes and to countdown in seconds from there, for example it is currently 10, 9, 8, 7, 6, 5 when 10 seconds is input.

What I want to happen is that the user inputs 5 and it counts down like so: 4:59 4:58 4:57

This is my current code:

    timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0, 0, 1);
    timer.Tick += timer_Tick;
    basetime = Convert.ToInt32(tbxTime.Text);;
    tbxTime.Text = basetime.ToString();
    timer.Start();
}


void timer_Tick(object sender, object e)
{
    basetime = basetime - 1;
    tbxTime.Text = basetime.ToString();
    if (basetime == 0)
    {
        timer.Stop();
    }

You can keep most of your existing code if you just make basetime a TimeSpan instead of an int . It's easy to set its value from Minutes or Seconds via the appropriate static method.

var basetime = TimeSpan.FromMinutes(5);

Then you can subtract one second from it like this:

basetime -= TimeSpan.FromSeconds(1);

And display it like this:

tbxTime.Text = basetime.ToString(@"m\:ss");

Finally, comparing it to zero is also trivial:

if (basetime <= TimeSpan.Zero)

See Custom TimeSpan Format Strings for more display options.

I think you can just make use of suitable formatting of TimeSpan class (you will surely find many examples on SO ). The easy example can look like this (I assume that you have a TextBox where you enter time and TextBlock which shows counter);

DispatcherTimer timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
TimeSpan time;
public MainPage()
{
    this.InitializeComponent();
    timer.Tick += (sender, e) =>
        {
            time -= TimeSpan.FromSeconds(1);
            if (time <= TimeSpan.Zero) timer.Stop();
            myTextBlock.Text = time.ToString(@"mm\:ss");
        };
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{ time = TimeSpan.FromMinutes(int.Parse((sender as TextBox).Text)); }

private void startBtn_Click(object sender, RoutedEventArgs e)
{ timer.Start(); }

Note that this is a very simple example. You should also think if DispatcherTimer is a good idea - it works on dispatcher, so in case you have some big job running on main UI thread it may not count the time properly. In this case you may think of using different timer, for example System.Threading.Timer , this runs on separate thread, so you will have to update your UI through Dispatcher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM