Question Stop Timer at a Random Time

glowtus

New member
Joined
Dec 12, 2011
Messages
4
Programming Experience
1-3
I'm working on a reaction time program where I'll be testing... well, reaction time of a user. For this program I'll need a timer to stop at a random time interval, say somewhere between 3 and 10 seconds. Anyone know of a technique to do this. I've done some research and it seems there are a bunch of different ways of generating a random number just not sure how to assign that number to a timer. Any advice would be much appreciated, thanks!
 
Here's a simple solution, without using a timer:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim randnum As New Random
Dim delay As Integer
delay = randnum.Next(2000, 10000)
Threading.Thread.Sleep(delay)
MessageBox.Show("STOP", delay.ToString)
End Sub
 
Here's a simple solution, without using a timer:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim randnum As New Random
Dim delay As Integer
delay = randnum.Next(2000, 10000)
Threading.Thread.Sleep(delay)
MessageBox.Show("STOP", delay.ToString)
End Sub

The simple things in life are often the worst. Calling Thread.Sleep on the UI thread is pretty much never a good idea.

glowtus, 99 times out of 100 you should be using Random.Next to generate a random number. That part of Solitaire's code is good. You should be creating one and only one Random object though, so do so using a member variable, not local. You would then use your number as the Interval for a Timer. Call Start and it will raise its Tick event in that many milliseconds, at which point you call Stop.
 
The simple things in life are often the worst. Calling Thread.Sleep on the UI thread is pretty much never a good idea.

glowtus, 99 times out of 100 you should be using Random.Next to generate a random number. That part of Solitaire's code is good. You should be creating one and only one Random object though, so do so using a member variable, not local. You would then use your number as the Interval for a Timer. Call Start and it will raise its Tick event in that many milliseconds, at which point you call Stop.


Alright, let me see what I can do tomorrow when I get back to the office. I'll post my code if I get lost (haven't used VB in about 8 years). Thanks for the help!
 
So if I had something like this:

Dim delay As Integer
Dim randnum As New Random
delay = randnum.Next(3, 10)
Timer1.Enabled = True
Timer1.Start()

How would I assign the value of the delay variable to the timer.stop?

Forgive me, like I said, I have not used this program in many years.
 
I think I may have figured out a different (maybe easier?) solution.

In the Timer_Tick Sub, I place a counter, so I'm saying if counter = randnum then blah blah blah. That seems to be working.
 
Back
Top