Setting a Random Timer Interval

underswamp

New member
Joined
Jan 5, 2014
Messages
1
Programming Experience
Beginner
Hi all,


I'm a beginner who's come to a roadblock. My goal is to make code that will beep randomly anywhere from1 to 30 seconds apart. Here is my code so far:


VB.NET:
Public Class Form1


    Private Sub Timer1_Tick(ByValsender As System.Object, ByVal e As System.EventArgs) HandlesTimer1.Tick
        Console.Beep()
    End Sub


    Private Sub Button2_Click(ByValsender As System.Object, ByVal e As System.EventArgs) HandlesButton2.Click
        Timer1.Stop()
    End Sub


    Private Sub Button1_Click(ByValsender As System.Object, ByVal e As System.EventArgs) HandlesButton1.Click
        Timer1.Start()
    End Sub
End Class


This beeps every one second. Now, Iwant to change the Timer Interval so that it will beep randomlybetween 1 and 30 seconds. Maybe later I will add options for the userto define the bounds, but for now, 1 and 30 are good numbers. I justdon't know how to apply a random number to my Timer Interval. Cananyone help? Thanks in advance.
 
Whenever you want to do something involving randomness, you use the Random class. You create a single instance and then make the appropriate method call(s) on that instance to generate one or more random numbers and then use them in whatever manner is appropriate for your scenario. In your case, if you want the Timer to Tick at a random interval then you need to set the Interval of that Timer to a random number. If you want the interval to be 1 to 30 seconds then you need to set the Interval to a random number between 1000 and 30000. If you want the interval to be consistent for each set of Tick events then you only need to set the Interval once before calling Start. If you want the interval to be randomised every time then you'll need to set it again after every Tick. You can test to find out for sure but it may be that you have to stop and start the Timer to get the new Interval value to be recognised. In that case, you'd call Stop, set the Interval and then call Start, all in the Tick event handler.

You should start by using the Help menu to open the MSDN documentation and read about the Random class. If you need examples, you'll find plenty online.
 
Back
Top