Intermediate 10 min read Control #27

Timer Control

Timer executes code at regular intervals. It's perfect for updating clocks, animations, auto-saving, and periodic tasks.

What is a Timer?

Timer is a non-visual component that fires Tick events at specified intervals. It runs on the UI thread, so it's safe for updating UI controls.

Code Example

// Setup Timer
timer1.Interval = 1000;  // 1 second
timer1.Enabled = true;   // Start immediately

// Tick event - fires every interval
private void timer1_Tick(object sender, EventArgs e)
{
    // Update a clock label
    lblClock.Text = DateTime.Now.ToString("HH:mm:ss");
}

// Control the timer
private void btnStart_Click(object sender, EventArgs e)
{
    timer1.Start();
}

private void btnStop_Click(object sender, EventArgs e)
{
    timer1.Stop();
}

// Auto-save every 5 minutes
private void Form_Load(object sender, EventArgs e)
{
    timerAutoSave.Interval = 300000;  // 5 minutes
    timerAutoSave.Start();
}

private void timerAutoSave_Tick(object sender, EventArgs e)
{
    AutoSaveDocument();
}

Exercise

Task: Create a stopwatch application.

  1. Add a Label to display time (HH:MM:SS).
  2. Add Buttons: Start, Stop, Reset.
  3. Use a Timer with 100ms interval.
  4. Track elapsed time in a variable.
  5. Format and display the time.
  6. Add a Lap button to record lap times.
Key Takeaway

Timer is essential for time-based operations. Use it for clocks, animations, auto-save, and periodic tasks. Remember to Stop() when done.