Search code examples
c#visual-studio-2010timerdelaystopwatch

Stop watch delay using timer c#


I want to add a stopWatch to my form but the one i made is lagging behind the time of other timer in pc. Can you give any solution for that? (My timer interval is 100). this is my code:

int min, sec, ms = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        Time.Text = min + ":" + sec + ":" + ms.ToString();
        ms++;
        if (ms > 9)
        {
            ms = 0;
            sec++;
        }

        if (sec > 59)
        {
            sec = 0;
            min++;
        }

    }

    private void timer_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

It working but with easy delay. I have tried to change so many things but none of them is working..


Solution

  • Timer's tick is not as precise as you think. So It would be better if you calculate the difference between start time and the time tick invoked.

    DateTime startTime = DateTime.Now;  
    private void timer1_Tick(object sender, EventArgs e)
    {
        Time.Text = DateTime.Now.Subtract(startTime).ToString(@"mm\:ss\.ff");
    }
    
    private void timer_Click(object sender, EventArgs e)
    {
        startTime = DateTime.Now;   
        timer1.Start();
    }