Search code examples
c#performancetimer

c# timer is going too fast if set


i'm trying to implement a simple countdown using Timer (using https://www.geoffstratton.com/cnet-countdown-timer code). it does work if i run the timer once but if i stop the timer or the timer goes to 00:00 the next time i'll start it, it will go 2x faster. if i stop it and start it again it will go 3x faster.

(my explaination may be not clear, i did a gif that demonstrate the problem) https://media.giphy.com/media/fQr7sX6LNRECvQpCYP/giphy.gif

i'm very novice at c#, i usually figure things out but i cant get what's happening here. I included the timer code. if somebody can help me with this it would be awesome! Thanks !!!

        private void btnStartTimer_Click(object sender, EventArgs e)
    {
        if (txtTimer.Text == "00:00")
        {
            MessageBox.Show("Please enter the time to start!", "Enter the Time", MessageBoxButtons.OK);
        }
        else
        {
            string[] totalSeconds = txtTimer.Text.Split(':');
            int minutes = Convert.ToInt32(totalSeconds[0]);
            int seconds = Convert.ToInt32(totalSeconds[1]);
            timeLeft = (minutes * 60) + seconds;
            btnStartTimer.Enabled = false;
            btnCleartimer.Enabled = false;
            txtTimer.ReadOnly = true;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();
        }
    }
    private void btnStopTimer_Click(object sender, EventArgs e)
    {
        timer1.Stop();
        timeLeft = 0;
        btnStartTimer.Enabled = true;
        btnCleartimer.Enabled = true;
        txtTimer.ReadOnly = false;
    }
    private void btnCleartimer_Click(object sender, EventArgs e)
    {
        txtTimer.Text = "00:00";
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (timeLeft > 0)
        {
            timeLeft = timeLeft - 1;
            // Display time remaining as mm:ss
            var timespan = TimeSpan.FromSeconds(timeLeft);
            txtTimer.Text = timespan.ToString(@"mm\:ss");
            // Alternate method
            //int secondsLeft = timeLeft % 60;
            //int minutesLeft = timeLeft / 60;
        }
        else
        {
            timer1.Stop();
            SystemSounds.Exclamation.Play();
            MessageBox.Show("Time's up!", "Time has elapsed", MessageBoxButtons.OK);
        }
    }

Solution

  • You need to unsubscribe from the event in your btnStopTimer_Click method:

    timer1.Tick -= timer1_Tick;