Question Timers - Problem

Syzis

Member
Joined
Apr 23, 2011
Messages
10
Programming Experience
3-5
Hello,

I have a basic question about timers, that I can't answer myself. It's annoying me.
My code is made to visit a website every X seconds.
There are two problems.

I Set the interval for 30 sec and the first visit should be right now, not after 30 seconds.
After that, wait 30 sec and navigate to another one (in a listbox). The problem is that the Timer is not waiting that time after the first visit.


My code:
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Timer1.Start()
    End Sub


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim a As Integer
        Timer1.Interval = 30000
        For a = 0 To ListBox1.Items.Count - 1
            WebBrowser1.Navigate(ListBox1.Items(a))
        Next a
    End Sub



Could you please help me?
 
First up, you shouldn't have a loop in your Tick event handler. The whole point of the Timer is to visit ONE web site every 30 seconds, right? The Timer Ticks every 30 seconds so, when the Timer Ticks, you should be visiting ONE web site, not EVERY web site. No loop. Obviously you need to know WHICH web site to visit, so you need to store that information somewhere, probably in the form of an index that you can use to get an item from the ListBox. You would obviously increment that value by one on each Tick, stopping the Timer when it went past the last index in the control.

Furthermore, you should not be setting the Interval in the Tick event handler. The Timer needs the Interval to know when to Tick, so it must be set BEFORE the Timer Ticks at all, so what point setting it in the Tick event handler?

As for the question, if you need the first web site loaded immediately then load the first web site immediately. Noone said that you can only display a web site from the Tick event handler. If you want a web site loaded as soon as the form is displayed then load the first web site from the Load event handler of the form. The most logical course of action would be to write a single method that loads the current web site, increments the index for the next web site and then Stops the Timer if there are no more web sites to load. You can then call that method from the Load and Tick event handlers.
 
Back
Top