How to Count Down Timer in C#

Muhammad Maisam Abbas Feb 16, 2024
How to Count Down Timer in C#

This tutorial will discuss the methods to create a count-down timer in C#.

Count Down Timer With the Timer Class in C#

The Timer class) is used to execute a function inside a separate thread in C#. We can use the Timer function to create a count-down timer in C#. The Timer.Interval property sets the interval between each tick of the timer in milliseconds. The Timer.Tick property performs a specific task at each tick. We can decrement the total time and display it to the user at each tick until the total time is zero. The following code example shows us how to create a count-down timer with the Timer Class in C#.

using System;
using System.Windows.Forms;

namespace countdown_timer {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
    }
    private int duration = 60;
    private void button1_Click(object sender, EventArgs e) {
      timer1 = new System.Windows.Forms.Timer();
      timer1.Tick += new EventHandler(count_down);
      timer1.Interval = 1000;
      timer1.Start();
    }
    private void count_down(object sender, EventArgs e) {
      if (duration == 0) {
        timer1.Stop();

      } else if (duration > 0) {
        duration--;
        label1.Text = duration.ToString();
      }
    }
  }
}

Output:

C# Count Down Timer

We created a count-down timer in the above code that counts from 60 to 0 seconds with the Timer class in C#. We set the Timer.Interval to be equal to 1000 milliseconds equal to one second, and we decremented the value displayed to the user with each tick until the value is equal to 0. We started the timer with the Timer.Start() function, and in the end, when the duration is equal to 0, we stopped the timer with the Timer.Stop() function in C#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp Timer