Syrne
Syrne

Reputation: 117

Nested timers? Trouble with logic on multiple simultaneous timer ticks

I'm trying to create a simple visual example and the first step is having a column of boxes (panels) move across the screen. So far I've accomplished that, but I'm also attempting to have each panel blink a few times, individually, while moving. The effect should be a type of 'round robin' loop where the first panel blinks a few times, then the second, then the third, etc, etc and repeat.

I'm quite new to VB and so far I've only been able to successfully make either only one panel blink or all of the panels blink, not each one individually. Here's my code so far:

Public Class Form1
    Public ticks As Integer
    Public p(4) As Panel

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        p(0) = Panel1
        p(1) = Panel2
        p(2) = Panel3
        p(3) = Panel4
        p(4) = Panel5

        ticks = 0
    End Sub

    Private Sub tmr1_Tick(sender As Object, e As System.EventArgs) Handles tmr1.Tick
        Dim i As Integer

        If ticks = 1 Then
            For i = 0 To 4
                Dim randomValue = Rnd()

                p(i).Top = 50 + 75 * i

                p(i).Left = randomValue * 120

            Next
        ElseIf ticks > 30 Then
            ticks = 0
        Else
            For i = 0 To 4
                p(i).Left += 20
            Next
        End If
        ticks += 1
    End Sub

    Private Sub tmr2_Tick(sender As System.Object, e As System.EventArgs) Handles tmr2.Tick
        Dim i As Integer

        For i = 0 To 4 'all of the panels blink at the same time..
            If p(i).Visible = False Then
                p(i).Visible = True
            ElseIf p(i).Visible = True Then
                p(i).Visible = False
            End If
        Next
    End Sub
End Class

As of right now, all of the panels blink while moving across the screen in random locations, I'm assuming this is because the for loop responsible for the blinking is nested within the ticking timer, so for each tick it runs through the loop fully.

I'm a little stumped on what should be some very simple logic, but please bear with me as I am a novice.

Thank you for any and all help!

Upvotes: 1

Views: 107

Answers (1)

OneFineDay
OneFineDay

Reputation: 9024

If I understand what you want, this would do it. They all blink now because they are all in the loop that occurs with each tick, this example changes each one by it's index in the array, and the index variable must be class level to retain it's value between ticks.

Private index As Integer
Private Sub tmr2_Tick(sender As System.Object, e As System.EventArgs) Handles tmr2.Tick
    p(index).Visible = Not p(index).Visible
    If index = 4 Then
        index = 0 
    Else
        index += 1
    End If
End Sub

Upvotes: 3

Related Questions