GhostPlays74
GhostPlays74

Reputation: 68

What is the best alternative for Sleep()

Im making an app using delphi and here is my code snippit

pnlMenu1.Visible := True;
Sleep(5000);
pnlMenu1.Visible := False;
pnlMenu2.Visible := True;

I need the user to still be able to do stuff while the Sleep() is running, but Sleep() stops the main thread which stops the program. Is there anything that i can replace the Sleep() with that will work? Like:

pnlMenu1.Visible := True;
//Wait 5 seconds but dont holt main thread
pnlMenu1.Visible := False;
pnlMenu2.Visible := True;

Upvotes: -1

Views: 311

Answers (2)

fpiette
fpiette

Reputation: 12292

Use a TTimer. Enable the time after having made pnlMenu visible and from the OnTimer event, put the rest of your processing.

You can use a "waiting loop" wich calls ProcessMessages, but this has plenty of difficulties (Re-entering events) so be careful testing your application when user clicks everywhere.

Upvotes: 2

GhostPlays74
GhostPlays74

Reputation: 68

I have found a solution. For anyone with same problem :

Add this somewhere in the code:

procedure Delay(dwMilliseconds: Longint);
var
iStart, iStop: DWORD;
begin
iStart := GetTickCount;
repeat
iStop := GetTickCount;
Application.ProcessMessages;
Sleep(1);
until (iStop - iStart) >= dwMilliseconds;
end;

Then replace 'Sleep(time)' With 'Delay(time)'

So:

Sleep(5000);

is replaced with

Delay(5000);

Upvotes: -1

Related Questions