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.