How to display on a label a timer counting back 5 minutes ? the code is not working.

jdoe doe 20 Reputation points
2024-01-14T11:57:32.9233333+00:00

in the form1 designer I added a timer. i can see that it's getting to the tick event and execute the UpdateTimer but the timer itself does nothing it stay on 05:00:00 and never start counting backward. so the tick event does work when i start the timer in the load event but the timer never count backward. the timer tick event the interval is set to 100ms and the UpdateTimer method:

private void timer1_Tick(object sender, EventArgs e)
{
    UpdateTimer();
}

DateTime now = DateTime.Now;
private void UpdateTimer()
{
    var target = now + TimeSpan.FromMinutes(5);
    var countdown = target - now;
    // Display time with milliseconds
    lblTimer.Text = $"{countdown.Minutes:D2}:{countdown.Seconds:D2}:{countdown.Milliseconds / 10:D2}";
}

in the form1 load even:

private void Form1_Load(object sender, EventArgs e)
{
    timer1.Start();
    UpdateTimer(); // Initial update
}
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,922 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,296 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Pinaki Ghatak 5,575 Reputation points Microsoft Employee
    2024-01-14T12:07:08.4433333+00:00

    Hello @jdoe doe

    The issue here is that the now variable is not being updated in the UpdateTimer() method. The now variable is set once when the form is loaded, and it never changes after that. This means that the countdown variable will always be the same, hence the timer appears to not count down. To fix this, you should update the now variable inside the UpdateTimer() method. Here’s how you can modify your code:

    private void timer1_Tick(object sender, EventArgs e)
    {
        UpdateTimer();
    }
    
    private void UpdateTimer()
    {
        DateTime now = DateTime.Now; // Move this line here
        var target = now + TimeSpan.FromMinutes(5);
        var countdown = target - now;
        // Display time with milliseconds
        lblTimer.Text = $"{countdown.Minutes:D2}:{countdown.Seconds:D2}:{countdown.Milliseconds / 10:D2}";
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        timer1.Start();
        UpdateTimer(); // Initial update
    }
    

    Now in the example given above code, the now variable is updated every time the UpdateTimer() method is called, which should allow your timer to count down correctly. If this answer solves your query, please note and accept this answer. This is helpful for community readers who may have similar questions.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.