Mirror

How to create a countdown timer (Views: 704)


Problem/Question/Abstract:

I was wondering if anyone knew of a way in which you were able to create a timer in which you could set a time (of about 20 minutes) and have it countdown by seconds and be able to stop it.

Answer:

Drop a TTimer onto your form. Set the INTERVAL using the object inspector to 1000. Set the control's Enabled property to False. Use another control, say a TEdit or TSpinEdit to set a variable with the total number of seconds you wish to wait. Use a TButton control to enable the timer. Use a second button to disable the timer. Double-click on the timer to create an OnTimer event handler. In the event handler, decrement the total time counter and check to see if it hit zero.

procedure TForm1.Edit1Change(Sender: TObject);
begin
  {the time is entered in seconds.  If you wish the time to be entered in "hh:mm:ss",
  you will have to parse it and put it into a total seconds format.}
  TotalTime := StrToInt(Edit1.Text);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Timer1.Enabled := true;
  Edit1.Enabled := false; {disable the ability to set the time}
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Timer1.Enabled := false;
  Edit1.Enabled := true; {re-enable the ability to set the time}
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  dec(TotalTime); {decrement the total time counter}
  Edit2.Text := IntToStr(TotalTime); {put the value in an edit box so he can see it}
  if TotalTime = 0 then {have we timed out?}
    {... Do something ...}
end;

Remark:

Rather than decrement a counter in the OnTimer event handler, it's better to compare the current system time to the original start time and calculate the difference. The reason for this is that timer messages are low priority, and it's very likely that some will be lost before being processed, causing any countdown scheme to be inaccurate.

<< Back to main page