Display a timer that loops every 15 seconds

I made this code, but there is a delay between the time loop showing on the screen and the exact elapsed time.

Timer t = new Timer();
int time = 15;
string timestr;
t.Interval = 1000;
t.Tick += new EventHandler(Time);

void Time(object sender, EventArgs e)
{
    if (time == 0)
    { time = 15; }
    if (time != 0)
    {
        time--;
        timestr = time.ToString();
        label.Text = timestr;
    }
}

Upvotes: 0

Views: 372

Answers (2)

Gajender Singh Thakur
Gajender Singh Thakur

Reputation: 34

I think you need to try this. Add the line Application.DoEvents() just before the end of Time function.

void Time(object sender, EventArgs e)
{
   if (time == 0)
   { time = 15; }
   if (time != 0)
   {
       time--;
       timestr = time.ToString();
       label.Text = timestr;
   }
   Application.DoEvents();
}

Upvotes: 0

LarsTech
LarsTech

Reputation: 81620

My guess is that you are off by one second since the timer won't fire its first event until that interval value is reached.

A quick fix would be to fire the event yourself when you start it:

t.Start();
Time(t, EventArgs.Empty);

Upvotes: 2

Related Questions