How to Program a Delay Using the Timer Function

Last reviewed: June 21, 1995
Article ID: Q96069
The information in this article applies to:

- Standard and Professional Editions of Microsoft Visual Basic

  for Windows, versions 1.0, 2.0, and 3.0
- Standard and Professional Editions of Microsoft Visual Basic
  for MS-DOS, version 1.0

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


Additional reference words: B_VBasic B_VBMSDOS 1.00 2.00 3.00 wait
KBCategory: kbprg kbcode
KBSubcategory: PrgOther


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: June 21, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.