What is VB6's most accurate delay method? If I want to "delay" for 1573ms, what would I use to get as close as "1573ms" as possible?
Stopwatch, sleep, timer, etc?
Printable View
What is VB6's most accurate delay method? If I want to "delay" for 1573ms, what would I use to get as close as "1573ms" as possible?
Stopwatch, sleep, timer, etc?
Not hard, as long as it is <20ms at a time.
Sleep(2000) will wait 2 seconds.
VB6 can't see values less than 20, but can do years in advance.
Almost all timings are linked to a hardware timer that is accurate to ~16ms. However this is still accurate enough for most applications, (unless you need 1ms accuracy)..
Now...
To your question..
Stopwatch : There is no such object by default in VB...
Timer : Accurate enough, however if the system is very busy, can be delayed by an unknown time. (although it is possible to calculate the delay after the fact.)
Sleep: will Pause the current application thread for the determined time, and is accurate to +- 16ms. Problem here is anything else running on this thread will not respond at all while waiting for the sleep timeout. (application will stop for that time)..
I'd like to bring up the SetTimer/KillTimer API here. Although I don't know about its accuracy (which seems to be pretty good, however), it does not have the flaws of the timer control and it does not hang the application. Good programming will use the time to at least perform some DoEvents while waiting for the timer elapse.
Put this code in a module to experiment with. The timer API will not work within a Form because of the CallBack routine. I have added a little sample to show how you use the timer API to replace the Sleep() API.
Code:Option Explicit
Private Elapsed As Boolean
Public Declare Function SetTimer Lib "user32" ( _
ByVal hwnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long _
) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal hwnd As Long, ByVal nIDEvent As Long _
) As Long
Private TimerID As Long
Private Sub StartTimer(ByVal IntervalTime as long)
TimerID = SetTimer(0, 0, IntervalTime, AddressOf TimerEvent)
End Sub
Public Sub TimerEvent(hwnd As Long, msg As Long, idTimer As Long, dwTime As Long)
'if it is a one shot then kill the timer here
KillTimer 0, TimerID
Elapsed = True 'signal that time is elapsed
'other wise the following is called in the interval you have specified
'timed code goes here
End Sub
'this is a sample 'sleep' replacement
Public Sub TSleep(SleepTime as Long)
StartTimer SleepTime
While Not Elapsed
DoEvents
Wend
End Sub
yes, my brother wof example is really great .use setTimer library .:wave: