Search code examples
vb.netloopswait

Loop and Time Delay


I've created a program which loads a webpage. Then I programmed 3 buttons which perform operations on the website. This functions fine.

But now I want to implement a button which will click Button1 one time, then it should wait 5 sec and then a loop should start and hit Button2 10 times. After this, the whole process should start again. The program is kind of a bot.

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Call Button1_Click(sender, e)
    Application.Wait(Now + TimeValue("0:00:10"))
End Sub

Application.Wait doesn't function because Application is not a member of System.Windows Forms.

How can I implement the delay? How can I implement the loop?


Solution

  • Based on comments, Threading.Thread.Sleep() gives you a problem that the website isn't loaded. The problem is that Threading.Thread.Sleep() stops your whole program from executing code as it freezes it. Here is how to make your program wait for some time.

    Public Class Form1
    
        Private Async Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
            MessageBox.Show("Commands before waiting")
            Await Wait(5000)
            MessageBox.Show("Commands after waiting")
        End Sub
    
        Private Async Function Wait(ByVal ms As Integer) As Task
            Await Task.Delay(ms)
        End Function
    
    End Class
    

    Just replace the MessageBox(s) with the commands you need before and after waiting.

    Note: This requires .NET Framework 4.5 or higher

    UPDATE based on Fabio comment:

    It can directly be done without need of Wait method like this:

    Public Class Form1
    
        Private Async Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
            MessageBox.Show("Commands before waiting")
            Await Task.Delay(5000)
            MessageBox.Show("Commands after waiting")
        End Sub
    
    End Class
    

    This also can be used in .NET framework 3.5 or higher but it needs some libraries which can be downloaded from here