How do I implement a delay in VB6
have used a Do-Loop that looked at the GetTicCount function of the WinAPI
'Some code goes here.....
'Now we wait for 100 msec...
x = GetTickCount
do while GetTickCount < x + 100
'Now we continue after the delay..
However, this ties up the computer in the do-loop.
Is there a better way without using a DO-Loop, like somehow putting the
application thread to sleep for say 100 msec?
Try the Sleep API.
Show quoteHide quote
"hamil" <firstname.lastname@example.org> wrote in message
> How can I implement a delay, of say 100 msec, in a subroutine? In the past
> have used a Do-Loop that looked at the GetTicCount function of the WinAPI
> like below.
> 'Some code goes here.....
> 'Now we wait for 100 msec...
> x = GetTickCount
> do while GetTickCount < x + 100
> 'Now we continue after the delay..
> However, this ties up the computer in the do-loop.
> Is there a better way without using a DO-Loop, like somehow putting the
> application thread to sleep for say 100 msec?
> Try the Sleep API.The Sleep() API puts the calling thread to sleep meaning your application is completely unresponsive during the wait, so you need to
combine both techniques but make the thread take lots of short 'naps' rather than one long sleep:
Private Declare Sub Sleep Lib "Kernel32.dll" (ByVal dwMilliseconds As Long)
Private Declare Function timeGetTime Lib "WinMM.dll" () As Long
Public Sub Wait(ByVal inMilliseconds As Long)
Dim SleepTime As Long, TimeNow As Long
Dim SleepTo As Long, SleepEnd As Long
Const MaxSleep As Long = 100
TimeNow = timeGetTime()
SleepTime = inMilliseconds \ 10
If (SleepTime > MaxSleep) Then SleepTime = MaxSleep
SleepTo = TimeNow + inMilliseconds
TimeNow = timeGetTime()
SleepEnd = SleepTo - TimeNow
If (SleepEnd <= SleepTime) Then Exit Do
If (SleepEnd > 0) Then Call Sleep(SleepEnd)
You can test it with something like this:
Dim StartTime As Double, EndTime As Double
StartTime = Timer()
Call Wait(5000) ' Wait for 5 seconds
EndTime = Timer()
Debug.Print Format$(EndTime - StartTime, "0.000")
It's not quite perfect since it doesn't take into account function calling overheads etc, but usually gets within a couple of
milliseconds of the target duration which should suffice for most applications.
Hope this helps,
- Microsoft Visual Basic MVP -
Other interesting topics
Functional IDE DLL call compiles to non-functional DLL call
Problem comparing double values
Programatically design a form
Verify a person's name?
Testing for MAPI , again
Search Engine CONTROL?
Date Time Picker Question
VB 6 UCase failing Compile Error: Can't find project or library
data structure equality
Default Property in VB6 Class