So, you're interested in having your functions act at specific time intervals, eh? Naturally you would turn to the Timer Control included with VB. Unfortunately, the timer control has a resolution of ~55ms. 55ms seems like a very short time to us, but to the computer, 55ms is an agonizingly long time. Don't torture your computer! Use accurate and high-resolution timing methods!
Private Declare Function GetTickCount Lib "kernel32" () As Long
Drool. I love this function. When I first stumbled upon it, I was amazed. Why didn't VB use this simple API call when they made their Timer Control? I guess it's one for the X-Files Mulder...
Anyways, what this function does is return the length of time that the system has been running in milliseconds. Since computers are frequently left on for days at a time, be sure that you use the Long data type as opposed to Integer when dealing with this control, or you may run into problems.
Determining when exactly an interval of time has passed is now a simple matter. All we have to do is store the current TickCount in a variable, and wait until the desired time length has elapsed:
TempTime = GetTickCount()
Do While DesiredTime > GetTickCount() - TempTime
'Do some things
The above example shows how we can execute some code for a specific length of time. What follows is an example showing how to execute some code every time an interval elapses:
ExitFunction = False
TempTime = GetTickCount()
Do While not(ExitFunction)
If DesiredTime > GetTickCount() - TempTime then
'Reset the temporary variable
TempTime = GetTickCount()
'Do some things
End If
Loop
Finally, the GetTickCount() function can also be used to benchmark your code. By this I mean you can use it to determine the time it takes to execute a specific chunk of code, thereby enabling you to tweak it for optimal speed (or slow it down, if that's what you're after). I have written a stopwatch like program to demonstrate how you would start, stop, and accumulate time through the use of the glorious GetTickCount API call. Check out the Files Page or click here to download now.
No computers were harmed or tortured during the making of this tutorial in accordance with the Geneva Convention of 1949.