An improved Sleep function

vegaseat 0 Tallied Votes 1K Views Share

The function Delay() allows access to other events during the delay. For instance a certain key could be used to interrupt a lenghty delay. The Win32 API function Sleep() ignores events, maybe it should be called DeepSleep().

//
// delay in milliseconds, uses the system time, also uses 
// Application.ProcessMessages, which allows access to other events 
// during the delay, the Win32 API function Sleep() does not
//
procedure Delay(msecs: integer);
var
  FirstTickCount: longint;
begin
  FirstTickCount := GetTickCount;
   repeat
     Application.ProcessMessages;
   until ((GetTickCount-FirstTickCount) >= Longint(msecs));
end;
nnolte 5 Newbie Poster

This code looks great however; when I incorporated it my CPU hit 100%!!!

tucode 0 Newbie Poster

tnx dude it helps!!

Member Avatar for andre.vanzuydam
andre.vanzuydam

Great function, exactly what I needed to poll a comport in a class I made

Duoas 1,025 Postaholic Featured Poster

I'm actually surprised you posted something like this, as it is a dangerous function -- especially for newbies who don't really know what the consequences of using it are.

Typically, a GUI should not be Sleeping/Delaying at all. If you must pause for some reason, use one of the Win32 Wait functions.

The purpose of a Sleep/Delay function is to block execution of the current thread for some amount of time.

If what you want to do, instead, is to schedule something to happen in the future, use a TTimer object, which properly integrates into the main event loop.

(What the code above does is create a potential nested event loop nightmare.)


Example of waiting for a key press:

program pak;
{$apptype console}
uses SysUtils, Windows;

function IsKeyPressed( ms: DWORD = INFINITE ): boolean;
  begin
  result := WaitForSingleObject( GetStdHandle( STD_INPUT_HANDLE ), ms ) = WAIT_OBJECT_0
  end;

begin
WriteLn( 'Press any key to wake me up.' );

repeat Write( 'Zzzzz' )
until IsKeyPressed( 500 );

WriteLn;
WriteLn( 'Hey, wha''d ''jou go ''n do that for?' )
end.

If you are doing something that is simply a lengthy process, either farm off to another thread (preferred) or simply check now and then that there is no waiting input using either a substitute Window Procedure or a global application state (such as disabling controls that should not be used while processing your long request).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.