CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Timer (loop)

  1. #1
    Join Date
    Mar 2004
    Posts
    13

    Timer (loop) [RESOLVED]

    Hi,

    I'm trying to make a program do X every 30 seconds. My timer only fires once. Here's my code:


    (in Declarations)
    Code:
    Option Explicit
    Dim Counter As Integer
    (in Form Load)
    Code:
    Timer1.Enabled = True
    Timer1.Interval = 1000
    Counter = "0"
    And my sub:
    Code:
    Private Sub Timer1_Timer()
    Counter = Counter + 1
    If Counter = 30 Then
        MsgBox "30 seconds has passed"
    
    End If
    End Sub
    I've tried changing things around a bit, and I've tried putting Timer1.Enabled=False followed by Timer1.Enabled=True after the MsgBox.

    What's wrong?

    Thanks.
    Last edited by rehto; March 22nd, 2004 at 05:08 PM.

  2. #2
    Join Date
    Jul 2003
    Location
    PA
    Posts
    124
    If this is all of your code, then you are missing the counter reset:

    private sub timer1()
    counter = counter + 1
    if counter = 30 then
    msgbox "30 seconds have passed, resetting counter", vbokonly
    counter = 0
    end if
    end sub

    If you don't reset the counter, your message event will never fire again.

  3. #3
    Join Date
    Mar 2004
    Posts
    13
    Wow! Thanks for the quick reply. It worked (easy, huh).

  4. #4
    Join Date
    Nov 2002
    Location
    Oakville, Ontario
    Posts
    48
    Are you possibly declaring the variable 'counter' inside the timer event sub? If so, it gets reinitialized each iteration and will never reach 30. And if this is the case, declare the variable at form level in general declarations.

  5. #5
    Join Date
    Jan 2003
    Location
    7,107 Islands
    Posts
    2,487
    What's the use of the Counter variable here when you can set the Interval of the timer object to 30000.

    Timer1.Interval = 30000
    Busy

  6. #6
    Join Date
    Jul 2003
    Location
    PA
    Posts
    124
    I commonly use iterative variables in timer loops for secondary functions that are not part of the timers primary function. This keeps the code footprint smaller, helps maintain memory utilization better, and helps increase speed. I was assuminmg that this is what he wanted to do. It is a common practice.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured