Waits and delays - learn how to create a delay

Visual Basic and Visual Studio .NET do not include a Wait command.  When working with instruments a Wait command can be particularly useful for adding a delay between a query and reply.  The most common example is to add a delay after sending a reset command to an instrument.  An instrument may buffer commands and any commands sent to an instrument that is resetting will likely be lost. There are several ways to introduce Waitfunctionality; sleep and delay are two common methods for creating a delay.

Sleep

For simple pauses that are several hundred milliseconds or longer you can use the Sleep API. Call the function with Sleep 1000 for a 1 second delay after declaring the function. Access this function anywhere inside the code after it is declared. For example:
Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
Private Sub Command1_Click()
    Debug.Print "Do you like to sleep?"
    Sleep 1000                          ' 1 sec sleep
    Debug.Print "Yes."
End Sub

Delay

For short delays of fractional seconds, or for a more accurate timer, use the timeGetTime Win API. timeGetTime returns the number of milliseconds since you started Windows. Use this function to create a delay function. The delay function uses the timeGetTime API as a reference to count the delay. Paste the following code into a module. Then when you want a delay of 50 milliseconds call the delay routine like this: delay 50.
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Public lngStartTime As Long
Public Sub delay(msdelay As Long)
    lngStartTime = timeGetTime()
    Do Until (timeGetTime() - lngStartTime) > msdelay
    Loop
End Sub

Comments