Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMake a loop that times out after a certain period
DescriptionThis example shows how to make a loop that times out after a certain period in Visual Basic 6.
Keywordstimeout, loop
CategoriesSoftware Engineering, Miscellany
 
When you click the FindFile button, the program looks for a specified file. If the program does not find the file, it sleeps for half a second and tries again. If it has not found the file after 5 seconds, the program gives up.
 
Private Sub cmdFindFile_Click()
Dim file_name As String
Dim found_name As String
Dim got_file As Boolean
Dim start_time As Date
Dim secs As Single

    prgFindFile.Min = 0
    prgFindFile.Max = 5
    prgFindFile.Value = 0
    prgFindFile.Visible = True

    ' Record the start time.
    start_time = Now

    ' Look for the file.
    file_name = txtFile.Text
    got_file = False
    Do
        ' See if the file is present.
        On Error Resume Next
        found_name = Dir$(file_name)
        got_file = (Err.Number = 0) _
            And (Len(found_name) > 0)
        On Error GoTo 0

        ' See if we have the file.
        If got_file Then Exit Do

        ' We did not find the file.
        ' Get the elapsed time.
        secs = DateDiff("s", start_time, Now)
        Debug.Print secs

        ' If elapsed time > 5 seconds, give up.
        If secs > 5 Then Exit Do

        ' Display progress.
        If prgFindFile.Value <> secs Then
            prgFindFile.Value = secs
            prgFindFile.Refresh
        End If

        ' Sleep for 1/5 second before trying again.
        Sleep 500
    Loop

    prgFindFile.Visible = False

    ' See if we found the file.
    If got_file Then
        ' We found the file. Process it.
        MsgBox "Found the file."
    Else
        ' We did not find the file.
        MsgBox "Did not find the file."
    End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated