Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# timer stop after some number of ticks automatically

Tags:

c#

winforms

timer

How to stop a timer after some numbers of ticks or after, let's say, 3-4 seconds?

So I start a timer and I want after 10 ticks or after 2-3 seconds to stop automatically.

Thanks!

like image 730
Razvan Ghena Avatar asked Aug 07 '13 10:08

Razvan Ghena


2 Answers

You can keep a counter like

 int counter = 0;

then in every tick you increment it. After your limit you can stop timer then. Do this in your tick event

 counter++;
 if(counter ==10)  //or whatever your limit is
   yourtimer.Stop();
like image 160
Ehsan Avatar answered Oct 23 '22 06:10

Ehsan


When the timer's specified interval is reached (after 3 seconds), timer1_Tick() event handler will be called and you could stop the timer within the event handler.

Timer timer1 = new Timer();

timer1.Interval = 3000;

timer1.Enabled = true;

timer1.Tick += new System.EventHandler(timer1_Tick);


void timer1_Tick(object sender, EventArgs e)
{
    timer1.Stop();  // or timer1.Enabled = false;
}
like image 33
beastieboy Avatar answered Oct 23 '22 07:10

beastieboy