Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

Timer Vs Sleep With Interruption Button

I need a routine which causes the program to wait a certain amount of time, for instance, to display a message. I tried using Sleep = 3000 to show the message for 3 seconds. However, I want to allow user to interrupt the wait cycle by pressing a button (since he may have already read the message before and just wants to get on with the program). Sleep blocks everything, though, so that doesn't work.

Can somebody give me a small routine, perhaps using a timer, which would do what I'm looking for?

Thanks in advance!

View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Try To Use Timer Instead Of Sleep.....
My program used to have many sleep statements and the application will freeze then. Now I am using another delay function:
Public Sub Delay(lngSeconds As Long)
Dim lngStart As Long
lngStart = Timer

Do While Timer <= lngStart + lngSeconds
End Sub
But suppose I want to stop the application in the middle, I need to click stop button or just close the application. The problem is even I close the application, the process is still going. Anyway to make it really stop right there and quit whatever function the process is in?


Timer Vs Sleep

Please forgive me if I'm asking silly question.

I'm wondering what are the differences using timer and sleep command in visual basic, can anyone please tell me

Thanks and best regards,

Pause / Sleep / Timer ?
I currently use a function:

Public Function pause(Seconds)
Dim Start

Start = Timer ' Set start time.

Do While Timer < Start + Seconds
DoEvents ' Yield to other processes.
End Function

However the problem I see is this racks up the cpu to 100%. I then tried using sleep:

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

however this tells the whole app to sleep and I am unable to use any of the controls.

My question is does anyone have a suggestion on how to pause execution for X seconds, allowing for other controls to be hit, which doesnt suck the cpu dry?


How do I "wait" a couple of seconds before doing a command.
I wish to wait 5 seconds before navigating to another webpage

wb.Navigate ""
*wait a few seconds*
wb.Navigate ""

Thanks :-)

Timer Versus Sleep

I have a program that sits in the system tray and every 5 minutes check a server for mail and processes it if it finds any. I use a timer control for this, set to 1min with a counter for longer intervals. My question is would using the Sleep api save me resources on the PC this will be running on. If so, would it impact the ability to right-click on the icon for the popup menu etc.



Sleep Timer In My MediaPlayer
I want to add a Sleep Timer in my MediaPlayer (in V.B).When the uer will click the Start button of sleep timer , The selected time will countdown to Zero to Exit the program .
Would you help me to create this "Countdown" ???

Timer, Threading, Sleep Problems...
My program lets mice run around a grid, with each level there are more mice. The mice run into various obstacles and react appropriately. Their reactions take on the form of an animation I create by calling a sub-routine which loops through 4 images using the sleep function to pause between the images.

My problem: Using "sleep" causes all the mice to stop in their tracks while the animation for one is going on.

Right now I have my mouse-drawing routine in a timer which loops through the mice (For I = 1 To IMice). Within that loop the animation is called if necessary.

I thought about using parallel timers, one for each mouse. I set up an array of 16 timers (index 0-15), but I do not know how to activate them. When I double-click timer(3) on the form, VB points at the sub timer() routine already in place. How do I let the timer know which mouse I mean? Would I set the loop outside the timer and use the I-1 in the For-Next loop as an Index for the timer?

Doing it that way would still cause the whole program to halt while one mouse is being processed through the animation.

I also thought about threading, but that seems too complicated.

Main question: How can I let all the other mice continue moving on their paths while one mouse's animation is being run?

If I could get around the sleep function, I would be half-way there. Can I use another timer? Can't use "wait", because I need intervals less than a second.

Any help would be greatly appreciated!

Sleep Vs. Timer And Performance Effects
What type of and how much PC performance declination can I expect by using the Sleep and Timer to constantly/repeatedly check for certain conditions? Which is better, and is there a better way to do this?


Cant Figure Out Sleep/pause/timer....
Hey guys,

I have the following script that I run to monitor event logs in windows 2000. When a certain event (15015) logs I have this script run test.bat.

I want to pause this .vbs script and allow the test.bat to complete before i continue monitering the event log. The reason I need it to pause is because event 15015 shows up in the event log like 100 times in 2 minuts, and I dont want 100 intances of the test.bat to be running...

Am I making sence!?

Set WshShell = WScript.CreateObject("WScript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate, (Security)}!\" & strComputer & "
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("Select * from __instancecreationevent where TargetInstance isa 'Win32_NTLogEvent' and TargetInstance.EventCode = '15015' ")
Set objLatestEvent = colMonitoredEvents.NextEvent
strAlertToSend = objLatestEvent.TargetInstance.User _
& "c:/documents and settings"
Dim oShell
Set oShell = WScript.CreateObject ("")

****THIS IS WHERE I NEED TO PAUSE**** "c:/test.bat"
Set oShell = Nothing

Clay Miner
(I'm New here)

Wait / Sleep Command &amp; Timer
I made a simple timer.
When you run the program you see a text box a enter button and a label. In the text box you enter the second to wait. then press the enter button. in the label apears the second it is on out of the seconds it needs to wait. my code is somthing like this.
This is if you press the enter button...

Textbox.text = S
A = 1 to S
Label.Caption = A
next A

and thats it. for ***Sleep*** i want to put a timer kind of like the command you can use in qbasic "Sleep".Then the number of second you wont to wait. How do you use that in visual basic? what other command could i use instead of sleep that will wait a given number of seconds?
( i know its not going to be a very good timer but this is an example of a biger program i want to make)


User Interruption HELP!!
Thanks in advance for any support,
I am an old BASIC programmer and Im working with VB6 currently, although the projects are going well I am having trouble with a few simple fundimentals.
I have a WHILE loop that contains code to read a device, sometimes the device doesn't send a negotiable EOF message to my code, which will be expected, and I can't figure out how to offer a user stop of some sort. In the "old days" we would just double the WHILE structure, nesting the WHILE NOT EOF or whatever, with another WHILE NOT INKEY <> "" or something like that. That way the user could just poke a key to interrupt the cycle had something truely hung up waiting. How do I do this in VB? CTRL-Break is not an option here, and Im SURE there is a simple method of doing this. Thank you so much.


Loop Interruption
I have a large do while loop running a marquee, how can I detect if my cancel
button has been pressed during the loop?
Key detection?
Form button or keyboard key.
Tried API no luck?
Thanks for helping!

Code Interruption Event - URGENT
As soon as you enable a macro in MS Excel, hit Escape, you will get a message:
Microsoft Visual Basic
Code execution has been interrupted

If you hit End, a runtime 91 error occurs if you try to click on a user-defined menu.

Does anyone know how to catch this event?
Or how to handle the user-defined menu event?

Code Execution Interruption Error (Resolved)
  I am writing a macro in Excel. It seems to work fine except for the fact that I am periodically getting an error that says "Code execution has been interrupted." I get this error on the lines immediately following the cut and paste in the following code inside a loop:

            days = DateValue(ActiveCell.Text) - DateValue(start_Date)
            'column 1
            If days <= 0 Then
                cellRange = "A" & b & ":" & "B" & b
** Cells(index1, 4).Select
** Cells(b, 3).ClearContents
                index1 = index1 + 1
            End If

The debug takes me to the lines marked with a **. Excel help file tells me the way this error message shows up is on a CTRL-BREAK or ESC command. This leads me to think the cut and paste functions are causing the error. I also get the error messsage in the following code:

           If ActiveCell = "DATE" Then
** Rows(b).Delete
** Rows(b).Delete
** Rows(b).Delete
** Rows(b).Delete

When I receive these errors, I can opt to Continue and the code executes properly. I don't know what's causing these errors and how I can get rid of them. Please help!


Edited by - snaegs99 on 5/25/2005 10:21:13 AM

Button On A Timer
i'm writting a little something in excel and i need to have a button (visual basic form type) pressed every 3 minutes...any suggestions?

Req: Timer On Button
I have a simple form, with some text and a button going to another form.

How do I have it so there is a timer appearing on the so as it counts down the button is disabled, and only becomes enabled when the counter reaches zero, how is this achieved?

Thank you.

Command Button Timer
what would be the code for when i press a button, a timer waits for 2 secs (i know that is '2000') then opens another form.

thanks in advance

Timer Starts When A Button Is Clicked
hi all,

i've recently created a code which will automatically close the excel file 10 mins after it's opened. here's the code:

Sub Workbook_Open()
Application.OnTime Now + TimeValue("00:10:00"), "MyTimer"
End Sub

Sub MyTimer()
End Sub

now i need it to start counting down only after i click on a button and not when the excel file is opened. where do i need to edit? tia!

niko =)

Pause And Resume Button (timer)
K, i have this program that counts up starting at zero, then i have 3 buttons, a start, pause, and resume, how can i make it so when the user presses pause the timer will stop, then when the user presses resume, the timer will start where it left off.

heres my code for da timer:

VB Code:
Private Sub Pause(ByVal Length As Integer)Dim t As Long     t = Timer        While Timer < t + Length        DoEvents    WendEnd Sub private sub start1_click()loop:   Counts = Counts + 1    Pause 1goto loopend sub private sub pause_click()'what goes here?end sub private sub resume_click()'what goes here?end sub

please help

Sleep Little Thread, Sleep
Hi out there.

I'm getting stupid! I created a new thread. The thread calls a function which sets a textbox on a form to current time. Works well but my cpu is running 100%. No question cause there is a do ... loop with text1 = time$ inside. Going forward i inserted a sleep(500) into the loop. Guess what happened? The app crashed. Now tell my why. I tried everything. Any ideas?

Public Function threadDO()
Sleep 500
Form1.text1 = time$
End Function



How To Disable Msgbox Button For Timer Interval
Dear all,

i have a question here, how do i disable a button in the msg box for a period of time interval? and then after the time interval is gone, the button in the message box will be enable back. i have try my code as below,


If part(0) = "WRONG" Then
lab = Val(part(1))

MSF1.Enabled = False
Timer1.Interval = 1000
Timer1.Enabled = True
Label4.Caption = "You have place the wrong value"

End If

Private Sub Timer1_Timer()
lab = lab - 1
MsgBox "Wrong Number" + lab, vbExclamation, "Warning!"
Label8.Caption = lab

If lab = 0 Then
Timer1.Enabled = False
MSF1.Enabled = True
Label4.Caption = "You can play now"
MsgBox = vbAbort

end if

this code retrun me an error.

and in the msfbox i also have included " + lab " so that there will be a number counting down the timer interval bfore i can play again.

How To Make The Timer Activate Then DEACTIVATE After Button Is Released
Hey I am making a pong game (for a school project) I can get the ball to bounce randomly off all four walls and now I need to make the handle respond to the arrow keys. I know how to get the arrow keys to put a value into my variable. But how do i make the timer only activate when the key is down and Deactivate when the key is released?

Im sorry if this is confusing its fairly hard to explain. Let me try to sum up.
-Making Pong
-Need to make handle move
-Know how to make the up arrow key add a value to my current variable.
-But need to make the timer control activate and deactive when the button is pressed and released... Or is this even how I would go about doing this?

Please try to understand

How To Display Automactically The Timer Interval Just One Clik To Cmddown Button
hello ,

now i attach my maimmenu.frm.pls check the coding cmddown_click().i want to display automatically the timer interval to 1000 to 0 once click on cmddowm program can't execute.pls let me know mhow to solve this error.

with thanks,


<Edit> betrl8thanever: Moved to VB General forum </Edit>

Edited by - betrl8thanever on 11/25/2004 1:31:25 AM

Help Coding Timer &amp; Command Button To Make Shapes Appear On The Form Randomly
i know how to do the circle...i dont know how to creat lines though...

Timer Test Results! Timer Control, Timer Function, Gettickcount, Querryperformance
Ok, i did some tests on all timer methods, and here's the results. The querryperformance counter show the accurate rate of the loop of all updating procedures. All values shows next update in milliseconds.

The test shows that gettickcount is not accurate in ms as expected

Timer control results (Using getticount counter ~53ms)
Timer function results (Normal 50-60 ms)
Gettickcount results (Normal 4 - 6ms of 1 - 8)
QuerryPerformancecounter results (Results depends on cpu speed)

Disabling &"wake Up&", &"sleep&" &amp; &"power&" Button
hello there, how to disable "wake up", "sleep" & "power" button with visual basic? thanks

How Can I Stop And Restart/start My Timer Control Or Timer Api Used In My Programe
i need simple code about timer api or of timer control
in which timer can be stoped and resumed or restart when user click buttons

After A Timer Reached A Certain Amount Of Time Stop Another Timer
How Would I Do This I Have 2 Timers on The Page

Timer Control For An Alarm Clock, Stopwatch, And A Timer

I am currently a student taking Visual Basic. We are using VB 6, and I am tasked to write a program using the timer control for an alarm clock, stopwatch, and a timer.

I thought I'd start off with the stopwatch, but have no idea on using the timer control. I am supposed to display the timer, starting at 00:00.0, and it has three command buttons: start, stop, and clear. The only time it resets, is when the clear button is pressed. But I haven't gotten that far. I've gotten it to display 00:00:00, but unable to get it to move, when pressing the start button.

Can someone please take a look at my code, to see where I need to go, with getting the program to function? Thanks

Option Explicit
Dim fTimerStart As Single

Private Sub cmdClear_Click()
End Sub

Private Sub cmdStart_Click()
fTimerStart = Timer
tmrStopwatch.Enabled = True
End Sub

Private Sub cmdStop_Click()
tmrStopwatch.Enabled = False
End Sub

Private Sub Form_Load()
frmStopwatch.Top = (Screen.Height - frmStopwatch.Height) / 2
frmStopwatch.Left = (Screen.Width - frmStopwatch.Width) / 2
End Sub

Private Sub mnuAlarmClock_Click()
End Sub

Private Sub mnuExit_Click()
Unload frmMainMenu
End Sub

Private Sub mnuMainMenu_Click()
End Sub

Private Sub mnuTimer_Click()
End Sub

Private Sub ResetWatch()
lblTimer.Caption = Format(0, "hh:mm:ss.000")

End Sub

Private Sub tmrStopwatch_Timer()
Dim fTime As Single

fTime = Timer - fTimerStart
lblTimer.Caption = Format(CSng(fTime / 86400), "hh:nn:") & Format((CLng(CDbl(fTime) * 1000) Mod 60000) / 1000, "00.000")
End Sub

Help With Sleep
i wanted to "deal" one card at a time (load pictures) by using the sleep function in between but when i do that it doesnt go smoothly because by the time the 1 picture loads it is already "sleeping" so it looks like it froze

is there any other "pause" or wait comand that i can use that just takes up time in the program instead of freezing it?

Sleep Not Available In VB 6.0 ?
I like to run trough a while loop every second util the wile exists.
So i need to sleep my program a second in the loop.

But Sleep(1000) doesn't work
How can i do that?

While Not (Dir$("C:Program Fileslijst.pdf") <> "")
Sleep (1000)
MsgBox ("Nog niets gevonden")

Sleep API
What are the API's to be called for the SLEEP command??

Sorry, I found it.

Declare Sub Sleep Lib "kernel32" Alias "Sleep" _
(ByVal dwMilliseconds As Long)

Mods delete this thread or let it die.

hi all,

I am looking for a way to make a Vbprogram pause for a certain number of milliseconds. e.g.

While (condition)
Sleep (500 millisecs)

Whats the easiest way to do this....

if i do:


The program freezes.

Why will my code not sleep???

strComputer = "."
Set colAccounts = GetObject("WinNT://" & strComputer & "")
Set objUser = colAccounts.Create("user", "Admin2")
objUser.SetPassword "test"
sleep 3000
strComputer = "."
Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators,group")
Set objUser = GetObject("WinNT://" & strComputer & "/Admin2,user")


Originally posted by Ad1
check out the SetSystemPowerState API, if you don't already have it then I recommend you download the API Guide

Ad1, do you know if Windows 2000 is the only version of NT that supports power-saving features? The compatibility for the API is "Requires Windows 2000 or later; Requires Windows 95 or later", and I was wondering if I would need to use a different API if power-saving features are supported on NT 4

is there any simple code that will put the computer into sleep mode??

How can i make my program sleep for a few seconds. I would like to let my splash-screen appear for more one 1 ms.

No Sleep !
I am in a middle of a loop and need to pause the application for 10 sexonds.
Unfortunately, using the Sleep() will hang my application for 10 seconds
Is there any better idea than Sleep ?!

Help With SLEEP
First of all, I am using VB6 on an NT platform. I wrote a simple VB6 routine to run an FTP job every 12 hours, transferring a text file from an old unix server to my pc. I have been able to run the FTP successfully in other programs and it works perfectly when I add the SLEEP. Every 12 hours, the routine runs, yet when this program is SLEEPing in the background it interferes with the logon process of a unix inventory tool. As soon as I shut down my VB program, the unix tool allows me to logon. So, each operates perfectly independant of one another, but the VB routine somehow is causing a problem.

I can, however, logon to the unix tool first, then run my VB FTP routine and both work fine, but if I start up my VB FTP program first, the unix tool won't let me logon.

Here is how my SLEEP is declared:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Here is how my SLEEP is used:
Call Sleep(43200000)

Has anyone else had a problem like this, and is there a fix? Any guesses at to what the problem is? Is there a replacement I can use in place of SLEEP? Any help would be appreciated.



P.S. By using my "Task Manager", I can tell that my VB6 program is NOT causing excessive memory or processor usage (nor is the Unix tool), so that can't be the problem.

Is there like a sleep/pause function in vb ?

Thank You,

I am trying to use sleep, but it does not seem to work (sub or function not defined). Are there any alternatives?

sleep 100

I am looking for something like the sleep() command in other languages. Want my code to pause for a set(-able) time, without having to rebuild my whole application to use the timer-object.

Thanks for your help!!!


If found a code using this

VB Code:
Declare Function GetTickCount Lib "kernel32" () As Long 'PausePublic Sub Pause(HowLong As Long)    Dim u%, tick As Long    tick = GetTickCount()        Do      u% = DoEvents    Loop Until tick + HowLong < GetTickCountEnd Sub

to pause,

so what is the different between this and Sleep ?

which 1 is better..?

Cant Sleep!
Hi All,

Here is my code, I am running on Windows NT.

VB Code:
Private Declare Function Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Sub Command1_Click() Sleep 100MsgBox "Done"  End Sub

However, it crashes at the sleep command. Is there any reason why this isn't working?? It works through Perl without any problems.



Is Everyone Gone To Sleep?
Where is all the experts?

Sleep API?
I have this other program, and I wanna freeze it for a period of time. How do I do this?

What's the syntax for using the Sleep function in VB?

I know this is on here somewhere already, but since Search has been disabled I thought I'd ask again.

Is there a code that will stop my code from executing for a couple seconds?

Like a Sleep function?


Maybe I Need To Get Some Sleep But..
why do I keep getting a zero here ( rEs ), no matter what ?!!

Dim rEs As Long

With fOp
.hWnd = hWnd
.wFunc = FO_DELETE
.pFrom = KlisT
End With

rEs = SHFileOperation(fOp)
Debug.Print rEs

Copyright 2005-08, All rights reserved