Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

How to wait for a few seconds

I am currently developing some software that waits for a couple (or more) seconds before continuing. I was using this:

While **check for seconds passed**

This does the trick but works horrors to the poor little processor.

There must be a way to wait without processing anything, just waiting, simply wait.

I tried a couple of API calls but they killed the event processing so my programming 'dies' until the wait ends.

Any help will be appreciated.

  • 3
1 Solution
To minimise affect on the processor you can do 2 things, use sleep and also calculate end time before loop. Example:

Const SecondsToTimeFactor As Double = 1#/(1440#*60#)

Dim TimeToStop As Date

DelaySeconds = 2 ' wait 2 seconds
TimeToStop = Now + (SecondsToTimerFactor * DelaySeconds)

Do While Now<TimeToStop
    Sleep 200 ' never sleep for more than 1 seconds (1000MS)

You need this declaration:

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

Warning to not attempt to sleep for more than 1 seconds in a form.  This will cause a form to appear to hang.  If the form receives a windows message like close form/got/lost focus etc.  Messages will be queued until the function wakes up.
I did some calculations and found that a program that waits in this way will use 1 seconds of CPU time every few weeks.
EsopoAuthor Commented:

You are good!!!

I tried it out, it sure works!

I played with it a bit, and realizaed even a 1 ms sleep will release the processor to a point where it seems no extra processing is being done.

The thing is, I need the form to continue fully functional while waiting, and 200 ms makes it look like hanging while the user types on a textbox or something like it.

Anyway, this sleep idea works like a charm, I think you deserve an award for this.

PS: I can't believe how a simple 1 ms sleep can release the processor almost completely.

Best regards
You should also checkout this link.  If you are not realy sleeping you should use the sleepex function.


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now