Home All Groups Group Topic Archive Search About

How do I implement a delay in VB6

Author
5 Jul 2005 9:55 PM
hamil
How can I implement a delay, of say 100 msec, in a subroutine? In the past I
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
   doevents
loop

'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?

Thanks

Hamil

Author
5 Jul 2005 10:04 PM
Michael C
Try the Sleep API.

Show quoteHide quote
"hamil" <ha***@discussions.microsoft.com> wrote in message
news:7B88737E-3D9D-4373-8D37-715F5A57DE9C@microsoft.com...
> How can I implement a delay, of say 100 msec, in a subroutine? In the past
> I
> 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
>   doevents
> loop
>
> '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?
>
> Thanks
>
> Hamil
>
>
>
>
Author
5 Jul 2005 10:30 PM
Mike D Sutton
> 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

    Do
        DoEvents
        TimeNow = timeGetTime()
        SleepEnd = SleepTo - TimeNow
        If (SleepEnd <= SleepTime) Then Exit Do
        Call Sleep(SleepTime)
    Loop

    If (SleepEnd > 0) Then Call Sleep(SleepEnd)
End Sub
'***

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,

    Mike


- Microsoft Visual Basic MVP -
E-Mail: ED***@mvps.org
WWW: Http://EDais.mvps.org/