HelpNeeder
HelpNeeder

Reputation: 6480

How to count down time until timer's next tick?

I have 2 timers. One of them is counting each time it ticks; while using steady interval, or one randomly generated. Second timer counts down to next tick in first timer.

As of right now I am doing as such:

    private void btnStart_Click(object sender, EventArgs e)
    {
        nextClick = int.Parse(nudClickInterval.Value.ToString());

        if (nudPlusMinus.Value != 0) tmrClickInterval.Interval = random.Next( int.Parse(nudClickInterval.Value.ToString()) - int.Parse(nudPlusMinus.Value.ToString()), int.Parse(nudClickInterval.Value.ToString()) + int.Parse(nudPlusMinus.Value.ToString()));
        else tmrClickInterval.Interval = int.Parse(nudClickInterval.Value.ToString());

        tmrClickInterval.Start();
    }

    private void tmrClickInterval_Tick(object sender, EventArgs e)
    {
        if (nudPlusMinus.Value == 0) tmrClickInterval.Interval = int.Parse(nudClickInterval.Value.ToString());
        else tmrClickInterval.Interval = random.Next(int.Parse(nudClickInterval.Value.ToString()) - int.Parse(nudPlusMinus.Value.ToString()), int.Parse(nudClickInterval.Value.ToString()) + int.Parse(nudPlusMinus.Value.ToString()));

        tmrNextClick.Interval = tmrClickInterval.Interval / 10;
        tmrNextClick.Start();
        content++;
        nextClick = tmrClickInterval.Interval;
        label1.Text = content.ToString();
    }

    private void tmrNextClick_Tick(object sender, EventArgs e)
    {
        if (nextClick <= 0) tmrNextClick.Stop();
        else
        {
            nextClick = nextClick - (tmrClickInterval.Interval / 10);
            lblNextClickCount.Text = (nextClick / 100).ToString();
        }
    }

I am setting up an interval of my count down timer by using first timer's interval dividing by 10. The problem is that I keep getting some errors such as: Value '0' is not a valid value for Interval. Interval must be greater than 0. at line: tmrNextClick.Interval = tmrClickInterval.Interval / 10;.

I'm not sure how to avoid my errors so I figure there might be a better way of counting down time until next timer tick. Plus, I'd want a count down in nice steady interval instead but I am getting quite confused and not sure how to manage this problem.

Hope for some help.

Upvotes: 0

Views: 1619

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112372

System.Windows.Forms.Timer has an int intervall. Dividing a number which is samller than 10 by 10 results in 0 (integer division!).

Try to use System.Timers.Timer, it has an interval of type double, or check for 0 and assign 1 in that case.

Upvotes: 2

Related Questions