Question

I'm beginner to programming. This is my code:

private void timer1_Tick(object sender, EventArgs e)
{
    sec++;
    textBoxSeconds.Text = sec.ToString();
    if (sec > 59)
    {
        sec = 0;
        textBoxSeconds.Text = sec.ToString();
        min++;
        textBoxMinutes.Text = min.ToString();
    }
}

time goes too fast;/ and it stops for few sec sometimes. Hope someone can help me:) *EDIT//* thanks for help:) it works, but i still have a problem i didnt menton earlier. time stops sometimes for 1-2 sec, idk why. maybe because of some loops?

Was it helpful?

Solution

This is the wrong approach. When you program starts just save a DateTime instance, i.e. startTime. In your timer tick handler calculate the difference between the current time and the start time and display that.

private DateTime startTime = DateTime.Now;

private void timer1_Tick(object sender, EventArgs e)
{
    var delta = DateTime.Now - startTime;
    textBoxSeconds.Text = delta.Seconds.ToString("n0");
    textBoxMinutes.Text = Math.Floor(delta.TotalMinutes).ToString("n0");
}

OTHER TIPS

Using your code, I can say probably you haven't set the timer Interval, so:

timer1.Interval = 1000; //1000 ms = 1 second

Then you can improve something in the Tick event:

private void timer1_Tick(object sender, EventArgs e)
{
    sec++;

    if (sec == 60)
    {
        sec = 0;
        min++;
    }

    textBoxSeconds.Text = sec.ToString();
    textBoxMinutes.Text = min.ToString();
}

So use the DateTime class, it's the best solution.

EDIT:

    DateTime startTime = DateTime.Now;

    void timer1_Tick(object sender, EventArgs e)
    {
        TimeSpan time = DateTime.Now - startTime;
        textBoxSeconds.Text = string.Format("{0:0#}", time.Seconds);
        textBoxMinutes.Text = string.Format("{0:0#}", time.Minutes);
    }

I agree about startTime - it is mandatory. I've also commented about DataTime.UtcNow - this is correct way.

About your second problem with 1..2 seconds lag - this is because timer's ticks racing side by side with seconds ticks.

1) If your timer will be triggered in 998ms instead of 1000ms, you can read the same amount of second and this number will stay before next tick.

2) Because application is not in real-time priority from OS point of view, it can be held for several seconds (e.g. for rendering multimedia stuff by other app) and you can notice a skip of 1 second...

To solve 1st reason and facilitate 2nd try to increase ticks count by decreasing Interval to 500 or 333.

For more advanced strategy that preserves your resources, you should still use 1000ms but synchronize you timer periodically with each half second crossing using dateTime.Milliseconds. That will maximize probability of avoiding side-by-side racing problem without extra ticks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top