Chase Ernst
Chase Ernst

Reputation: 1155

Timer Inside Label

I am trying to put a countdown timer insde my label in my program, but when I run the program it doesn't countdown. It skips right to one, and that's it.

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Dim Time As Integer = 11
    Do Until Time = 0
        ClockLabel.Text = "Compacting database in: " & Time
        Time -= 1
    Loop
End Sub

I also have started the timer and declared the interval to 500 in the Form_Load routuine.

Upvotes: 3

Views: 4112

Answers (4)

dbasnett
dbasnett

Reputation: 11773

If you want the code to show the actual amount of time then the code could look like this.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'start the count down
    CompactTimer.Interval = 500
    CompactTimer.Start()
    stpw.Stop()
    stpw.Reset()
    stpw.Restart()
End Sub

Dim stpw As New Stopwatch
Dim countdown As New TimeSpan(0, 0, 11) 'length of countdown in seconds

Private Sub CompactTimer_Tick(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Dim togo As TimeSpan = countdown - stpw.Elapsed
    If togo.TotalSeconds > 0 Then
        ClockLabel.Text = String.Format("Compacting database in: {0} secs.", togo.TotalSeconds.ToString("n0"))
    Else
        CompactTimer.Stop()
    End If
End Sub

Relying on the interval to mark the passing of time will result in inaccuracy.

Upvotes: 2

matzone
matzone

Reputation: 5719

make a static var ..

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Static Time As Integer = 11

    ClockLabel.Text = "Compacting database in: " & Time
    Time -= 1
    If Time = 0 Then CompactTimer.Stop

End Sub

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564323

The loop happens each time the timer ticks. You most likely want something like:

Dim time as Integer = 11 ' Declare outside
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    If Time = 0 Then
        CompactTimer.Enabled = False ' Disable timer
        ClockLabel.Text = "Compacting database now"
    Else
        ClockLabel.Text = "Compacting database in: " & time
        time -= 1
    End If
End Sub

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

Get rid of the loop and declare the Time variable outside the scope.

Dim Time As Integer = 11

Private Sub CompactTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
                              Handles CompactTimer.Tick
  If Time >= 0 Then
    ClockLabel.Text = "Compacting database in: " & Time
    Time -= 1
  Else
    CompactTimer.Stop
  End If
End Sub

Upvotes: 5

Related Questions