'Traffic light and infinite loop countdown

I have programmed a traffic light on visual basic 6.0 but I cant seem to program the countdown(10-0) to be on infinite loop at every light i.e it should countdown from 10 to 0 before each light shows. Here is my code

Private Sub Timer2_Timer()
    If Label1. Caption = 0 Then
        Timer2.Enabled = False
        MsgBox ("go")
    Else
        Label1. Caption = Label1. Caption - 1
    End If
End Sub

the countdown continues to 1,-2,-3,-4 and so on but I want it to start from 10 again after counting from 10 to 0. How do I put it on endless loop on visual basic 6.0

vb6


Solution 1:[1]

Instead of:

Timer2.Enabled = False

do something like:

Label1.Caption = 10

That way the timer will keep running forever, and will reset to 10 every time it reaches 0.


Also, to make the code a little more robust, you might take this approach:

Private Const maxCounter As Integer = 10
Private counter As Integer

Private Sub form_Load()
    counter = maxCounter
End Sub

Private Sub Timer2_Timer()
    If counter = 0 Then
        counter = maxCounter
        MsgBox ("go")
    Else
        counter = counter - 1
    End If

    Label1.Caption = counter

End Sub

One advantage is that your code does not depend on how you set the Caption property at design time. And secondly it is a little more modular and understandable in that the functional logic (how the counter is managed) and the display logic (how the caption is set) are mostly distinct.

Also, using a constant maxCounter just means you don't have to repeat the value in different places, and it can be changed easily without introducing discrepencies.

Obviously this is a small program but these are good programming principles to think about which benefit larger programs tremendously.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1