count up/down with Timers

Joined
Jan 5, 2008
Messages
8
Programming Experience
Beginner
Hello all, I've been looking online for a bit using Google but I couldn't find a code that worked or I understood easily. I'm trying to make a timer activate and count up/down to/from 2 mins and 30 seconds on the press of a button. Does anyone know the code? Thanks in advance.
 
I think you are confused as to what a Timer actually is. A Timer is like an alarm clock. You tell it the length of time to wait and at the end of that time period it raises an event. It keeps on raising that event after the specified time period until you tell it to stop. That's all a Timer does. Timers are not stopwatches. There's a Stopwatch class for that.

So, what can you do? Presumably you want this countdown to be displayed to the user. Presumably you want to display the time remaining to the user and have this display refreshed every second. You can use a Timer to raise a Tick event every second, allowing you to refresh the display. That would be the sum total of the Timer's involvement.

You could do it like this:
VB.NET:
Private endTime As Date

Private Sub Button1_Click(ByVal sender As Object, _
                          ByVal e As EventArgs) Handles Button1.Click
    Me.endTime = Date.Now.AddSeconds(150)
    Me.RefreshCountdown()
    Me.Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, _
                        ByVal e As EventArgs) Handles Timer1.Tick
    Me.RefreshCountdown()
End Sub

Private Sub RefreshCountdown()
    Dim timeRemaining As TimeSpan = Me.endTime - Date.Now

    If timeRemaining <= TimeSpan.Zero Then
        Me.Timer1.Stop()
    End If

    Me.Label1.Text = String.Format("{0}:{1:00}", _
                                   timeRemaining.Minutes, _
                                   timeRemaining.Seconds)
End Sub
 
yeah but remember to disable the timer as parter of the timer code so that it doesn't trigger a second time...

Personally if I was using a timer to do this, I'd have a module level variable with the start time and the end time and another to indicate if the event had been triggered. The button would set all. In the timer, I'd have code that activated if StartTime >= EndTime and set the flag for the trigger to True so that the timer would skip over it subsequently. And added code to disable the timer as I said in the Timer event and to enable it in the button. The timer interval would be quite low to ensure accuracy, say 500 or so. That'd work while keeping the cpu to a fair minimum. It's not the most effecient way of doing it but it's pretty easy to implement and accurate.

But that's just me.
 
Back
Top