Simple example that increments a lable every millisecond using a timer

ejleiss

Active member
Joined
Oct 1, 2012
Messages
37
Programming Experience
1-3
Hi I was wondering if someone could post some simple code using a timer that would increment a label ever millisecond?
Thank you.
 
Hi,

To demonstrate what you have asked for create a new form, add a label control and a timer control to the form and then set the properties of the timer control to:-

Enabled = True
Interval = 1 - This being 1 millisecond

Then replace the code behind the form with the following code:-

VB.NET:
Public Class Form1
 
  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Label1.Text = FormatDateTime(Now, DateFormat.LongTime)
  End Sub
 
  Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    Label1.Text = FormatDateTime(Now, DateFormat.LongTime)
  End Sub
End Class
That sorted and done, you can see the label only changes every second (1000 milliseconds) but you have to realise that the code has fired 1000 times in each second, so long as your PC can keep up with that sort of performance requirement?

There are not many situations I can think of that require a timer to fire every millisecond so the question you have to ask yourself is what is the real frequency that you need something to happen since in most situations this would be totally unnecessary and the processor usage is a total waste of performance not to mention the memory usage.

Cheers,

Ian
 
The documentation for the Timer class, which you have no doubt read by now, says that you cannot rely on the Tick event being raised any more regularly than ever 55 milliseconds. Even at that speed though, the human eye is not going to be able to spot individual time values in a Label. Try setting the Interval to something like 73 and see if it's any less meaningful. If you're using this for something like a Stopwatch, you should get the current time when you stop it rather than using the last displayed time. That said, are you going to be accurate to within 73 milliseconds anyway?
 
Back
Top