'How do you stop a timer inside it's own tick function?

I have a problem, where I want to stop my timer inside it's own function, bit for some reason, it doesn't work:

private void timer1_Tick(object sender, EventArgs e)
{
    if (timer1_able)
    {
       Random rnd = new Random();
       int length = buttonListforBot.Count();
       int number = rnd.Next(1, length);
       buttonListforBot[number].PerformClick();
       label1.Text = counter.ToString();
       if (counter == 2)
       {
           timer1_able = false;
           timer1.Stop();
       }
}

So when I stop it, for some reason, it goes back to itself, and loops trough again



Solution 1:[1]

This will be fine:

int counter = 0;

button1_Click(object sender,EventArgs e){
  counter = 0;
  timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
   
   counter++;
   label1.Text = counter.ToString();

   if (counter >= 2)
   {
       timer1.Stop();
   }
}

You don't need extra booleans to control if some code runs; the Tick event doesn't fire for a stopped timer

Use >= for your counter check; it's safer than using == just in case one day some code addition means that the counter jumps past 2 and misses it. Always use ranged checks not exact equality checks where possible

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caius Jard