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.
- Add a Label to display time (HH:MM:SS).
- Add Buttons: Start, Stop, Reset.
- Use a Timer with 100ms interval.
- Track elapsed time in a variable.
- Format and display the time.
- 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.