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!
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!
i generally talking because you didn't mention which timer, but they all have ticks... so:
you'll need a counter in the class like
which you'll initialize in the start of your timer, and you'll need a dateTime like
which you'll initialize in the start of your timer:
and in your tick method you'll do:
here is a full example
When initializing your timer set a tag value to 0 (zero).
Then, with every tick add one...
and check if it reached your desired number:
Use this same technique to alternate the timer associated event:
To check elapsed time (in seconds):
Assuming you are using the
System.Windows.Forms.Tick
. You can keep track of a counter, and the time it lives like so. Its a nice way to use the Tag property of a timer. This makes it reusable for other timers and keeps your code generic, instead of using a globally definedint counter
for each timer.this code is quiet generic as you can assign this event handler to manage the time it lives, and another event handler to handle the specific actions the timer was created for.
You can keep a counter like
then in every tick you increment it. After your limit you can stop timer then. Do this in your tick event
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.