In addition to the timer control, which can be used to regularly trigger events, Visual Basic provides the Timer function which will tell you the number of seconds that have elapsed since midnight on the system clock.  This can be used to measure elapsed time intervals.

In this activity, we will create a simple demonstration application that measures the elapsed time from when the user clicks a Start button until they click a Finish button.

Create a form with the following controls on it:

Here is the code you will need:

Dim start, finish, elapsed

Private Sub cmdExit_Click()
     Unload Me
End Sub

Private Sub cmdFinish_Click()
     finish = Timer  'stop timing
     elapsed = finish - start   'calculate time difference
     lblTotalTime.Caption = "Elapsed time was " & elapsed & " seconds"
End Sub

Private Sub cmdStart_Click()
      start = Timer    'start timing
End Sub

You will notice that the time is given to six decimal places.  By using this code: 

elapsed = (Int((finish - start) * 100)) / 100 

you can make it show the time to 2 decimal places.  Can you see how it works?

In this activity we will create a reaction timer.  The user will click the Go button and after a random time interval, an image will appear.  The application will measure the time it takes the user to click on the image once it has appeared.  

Set up a form as below:

*Reaction timer based on code written by Bruce Jeffrey, Geilston Bay High School

Set properties for the lines as follows: (This sets the boundaries for where the image can appear)

X1 X2 Y1 Y2
line1 15 15 20 950
line2 15 760 950 950
line3 760 760 20 950
line4 15 760 20 20

You can use any image you like, but its size should be no more than approx 120 x 120 twips, otherwise it will be placed outside the square.

Here is the code you will need:

Private Sub CmdGo_Click()
    Randomize
    TmrGame.Interval = Int(Rnd * 5 + 1) * 1000
    TmrGame.Enabled = True
    ImgHitMe.Left = Int(630 * Rnd) + 20
    ImgHitMe.Top = Int(805 * Rnd) + 25
    CmdGo.Visible = False
End Sub

Private Sub TmrGame_Timer()
    ImgHitMe.Visible = True
    start = Timer
End Sub

Private Sub ImgHitMe_Click()
    TmrGame.Enabled = False
    finish = Timer
    time = finish - start
    ImgHitMe.Visible = False
    CmdGo.Visible = True
    txtResult.Text = time
End Sub

Private Sub cmdEnd_Click()
    Unload Me
End Sub

 

Modify the code so that the image can take between 1 and 10 seconds to appear.

Modify the code so that the time is given to 2 dec places only.

Add instructions for the user so that they know what to do.

Modify the code so that it keeps a record of times for the user, then calculates their average time.  

Hints:

The following line of code will add the new scores on to the text box:

txtResult.Text = txtResult.Text & time & vbCrLf

(note: vbCrLf makes a new line)

You will need to keep tally of how many tries they have had, as well as the total time they have taken.