Delay using nesting in For Next Loop

I am new to Visual Basic and am using the 2005 Express Edition.
Can anyone please tell me why the following code does not produce 10 Beeps with a short delay between each one.

For
Int As Integer = 1 To 10
     
For Tim As Integer = 1 To 50
           Beep()
      Next Tim
Next Int



Answer this question

Delay using nesting in For Next Loop

  • ericsstoll

    Be careful with threading sleep for any significant delays as the delay if in a looping construct can make the applications rather unresponsive as the process and UI are on the same thread and your just suspending the thread (therefore the UI as well)


  • maheshbabui

    Because the Beep is inside the inner for-loop, it will be executed 10*50 = 500 times. If you want just 10 beeps, it has to be outside of the inner loop:



    For Int As Integer = 1 To 10
        Beep()
        For Tim As Integer = 1 To 50
        Next
    Next Int

     


    However, using a for-loop to delay code execution is not appropriate on modern computers. If the compiler is not smart enough to remove the empty loop in the first place, computers today have very different speeds, resulting in a different delay length. Plus, a loop of 1..50 is executed very fast these days... The appropriate method to delay is System.Threading.Thread.Sleep(...).

  • J.M. Dussault

    The way your code is written it should produce 500 beeps.  Every time the the tim loop runs it should beep 50 times and you run the tim loop ten times.  Try moving the beep to the line right after next tim.




  • AvinashA

    system.threading.sleep(10) will make the program wait 10 milliseconds before continuing.

    http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfSystemThreadingThreadClassSleepTopic.asp

  • M-Studios

    Thank you Ken and Daniel.  I dabbled with VB4 way back when.  Nested For Next Loops just aren't up to it. Big Smile
    Have searched for info on 'Sleep' but have had no joy.
    Can you give me a clue

  • zkent

    Remembered the 'Timer' Control.  Got it to work with good effect.
    Now have a countdown Timer. Big Smile

  • Sergio G

    Thanks Ken. The language is not quite as Basic as it used to be. Smile
    It's back to the drawing board.  I'm glad it's a hobby and I just do it for fun.
    I've moved up from Windows 98 to XP with a new computer so I have plenty to accupy my mind at the moment. Thanks again.
    Steep

  • Delay using nesting in For Next Loop