With the latest threading library from Delphi XE7, it’s been quite easy to start a procedure with a delay. The TTask does its job very well:
TTask.Create( procedure begin Sleep(1000);//delay of 1s ShowMessage('Hello'); end).Start;
This is very easy but it has one big issue – you cannot easily stop the execution before the delay limit is reached and it can be used only in the latest Delphi versions. So I came up with my own alternative:
TOCallWithDelay.Create(Self, 1000, procedure begin ShowMessage('Hello'); end);
The first parameter is the component owner – if the owner is destroyed (e.g. you close the dialog before the limit), the procedure call won’t be executed. The class works in Delphi 5 and newer on all supported platforms, including mobile/ARC. FPC/Lazarus is supported as well.
If you want to stop the object in the future, use:
procedure TForm1.Btn1Click(Sender: TObject); var xCall: TOCallWithDelay; begin TOCallWithDelay.Create(Self, @xCall, 1000, procedure begin ShowMessage('Hello'); end); xCall.Free;//stop TOCallWithDelay -> do not call the method end;
Download the source code with a simple test project: