How to Program a Delay Using the Timer Function (96069)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 2.0
  • Microsoft Visual Basic Standard Edition for Windows 3.0
  • Microsoft Visual Basic Professional Edition for Windows 2.0
  • Microsoft Visual Basic Professional Edition for Windows 3.0
  • Microsoft Visual Basic for MS-DOS

This article was previously published under Q96069

SUMMARY

You can delay execution of your code for a specific time interval by using the Timer function.

With Visual Basic for MS-DOS, you cannot use the SLEEP statement to do this while forms are showing. An attempt to do so causes this error:
Invalid when forms are showing.

To use the Timer function to pause for a number of seconds, store the value of Timer in a variable. Then use a loop to wait until the Timer returns a a specified number of seconds greater than the stored value. If the delay loop will execute when midnight passes, compensate by reducing the starting Timer value by the number of seconds in a day (24 hours * 60 minutes * 60 seconds). Calling DoEvents from within the loop allows events to be processed during the delay.

MORE INFORMATION

Code Example

Sub Form_Click ()
   Print "hello ";
   Call Pause(2)  ' delay for 2 seconds
   Print "world"
End Sub

Sub Pause (ByVal nSecond As Single)
   Dim t0 As Single
   t0 = Timer
   Do While Timer - t0 < nSecond
      Dim dummy As Integer
      dummy = DoEvents()
      ' if we cross midnight, back up one day
      If Timer < t0 Then
         t0 = t0 - clng(24) * clng(60) * clng(60)
      End If
   Loop
End Sub
				

Modification Type:MinorLast Reviewed:8/16/2005
Keywords:KB96069