title: What is the best way to program a delay in Delphi?
body: <p>A Delphi application that I'm working on must delay for one, or sometimes two, second(s).  I want to program this delay using the best practices.  In reading entries about Delphi's Sleep() method on stackoverflow, I found these two comments:</p>
  
  <blockquote>
    <p>I live by this maxim: "If you feel the need to use Sleep(), you are doing it wrong." –  Nick Hodges Mar 12 '12 at 1:36</p>
    
    <p>@nick Indeed. My equivalent is "There are no problems for which Sleep is the solution." –  David Heffernan Mar 12 '12 at 8:04</p>
  </blockquote>
  
  <p><a href="https://stackoverflow.com/questions/9656017/strange-behaviour-of-function-sleep-used-in-repeat-until-in-delphi#_=_">comments about Sleep()</a></p>
  
  <p>In response to this advice to avoid calling Sleep(), along with my understanding about using Delphi's TTimer and TEvent classes, I have programmed the following prototype. My questions are:  </p>
  
  <ol>
  <li>Is this a proper way to program a delay?</li>
  <li>If the answer is yes, then why is this better than a call to Sleep()?</li>
  </ol>
  
  <hr>
  
  <pre><code>type
    TForm1 = class(TForm)
      Timer1: TTimer;
      procedure FormCreate(Sender: TObject);
      procedure Timer1Timer(Sender: TObject);
  
    private
    public
      EventManager: TEvent;
  
    end;
  
    TDoSomething = class(TThread)
  
    public
      procedure Execute; override;
      procedure Delay;
    end;
  
  var
    Form1: TForm1;
    Something: TDoSomething;
  
  implementation
  
  {$R *.dfm}
  
  procedure TDoSomething.Execute;
  var
    i: integer;
  
  begin
    FreeOnTerminate := true;
    Form1.Timer1.Interval := 2000;       // 2 second interval for a 2 second delay
    Form1.EventManager := TEvent.Create;
    for i := 1 to 10 do
      begin
        Delay;
        writeln(TimeToStr(GetTime));
      end;
    FreeAndNil(Form1.EventManager);
  end;
  
  procedure TDoSomething.Delay;
  begin
    // Use a TTimer in concert with an instance of TEvent to implement a delay.
    Form1.Timer1.Enabled := true;
    Form1.EventManager.ResetEvent;
    Form1.EventManager.WaitFor(INFINITE);
    Form1.Timer1.Enabled := false;
  end;
  
  procedure TForm1.FormCreate(Sender: TObject);
  begin
    Something := TDoSomething.Create;
  end;
  
  procedure TForm1.Timer1Timer(Sender: TObject);
  begin
    // Time is up.  End the delay.
    EventManager.SetEvent;
  end;
  </code></pre>