The main reason for inaccuracy in the Timer control is that they have
relatively low priority in the Windows scheme of things and other
processor-intensive apps running can delay the Timer from its appointed
rounds. Up through VB4 we were told that Timers were non-reentrant, which
meant that the Timer1_Timer event could not fire if the last event was still
running, in other words, if you set an interval of 1000 ms and the code in the
event took longer than a second to execute you could miss an entire cycle.
Someone told me this is no longer true in VB5 but I've never tested it and I'm
not sure it's true. In any event, the fix is to use the Timer FUNCTION to
keep track of elapsed time. The Timer function returns the number of seconds
which have elapsed since midnight, and is pretty accurate if you don't need
granularity finer than 1 second. Use a Timer control set to fire every 100 ms
or so to check the value of the timer function. Try this code in the
Timer1_Timer event.
Static lSeconds As Long
Dim lNow As Long
lNow = Timer
If lNow <> lSeconds Then
'''Do your stuff here.
lSeconds = lNow
End If
Because lSeconds is Static, it keeps its value between events. If lNow is
greater than lSeconds, at least one second has elapsed. If lNow is less than
lSeconds, we have crossed midnight, and the Timer function has been reset to
zero, and a second has elapsed. This code should give you self correcting
accuracy to within 100 ms or whatever interval you set for the Timer Control.
(The code is untested, but it should be close.)
Lee Weiner
weiner AT fuse DOT net
Quote:
>I have a very simple countdown program that I'm writing to help me learn the
>basics of VB. I come to notice that the timer control is less than perfect,
>even for 1 second intervals. I've noticed that after a period of time (not
>exactly sure how much, I wasn't watching for this) the countdown had lost
>time. So, I realign with the system clock once an hour.
>Is there any better way to do this? All my timer_Timer event proc does is
>decrement a variable or two, and then update the picture in a picturebox or
>two using LoadPicture. Granted, this may be a lot for a timer event... I
>don't know. If there isn't a better way, I can live with my current
>implementation.
>Any ideas?
>Also, yes, I am a newbie... and the only book I have available to me right
>now besides the online ones is the paper copy of the Programmer's Guide. I
>don't need a book on programming concepts as I've been programming w/ C and
>C++ for a WHILE... just one that shows the implementation of different
>things using VB. Any suggestions?
>Thanks a lot for your help.
>- Greg Hurlman