Re: Timer...

[ DelphiLand Discussion Forum ]

Posted by webmaster Guido on May 02, 2003 at 17:15:14:

In Reply to: Timer... posted by Chris H on April 30, 2003 at 11:28:19:

: I'm struggling in Delphi (im only a beginner) but I'm hoping to create a label that would time in seconds once a user was to press a button till the user has finished to tell them how long they've been running the program.
: Any help would be greatly appreciated as I am at a loss.
: Thanks again,
: Chris
: ps. I can get a label to appear displaying the date and time but just can't get it to count in seconds.

Here's an example project, that calculates the time that has elapsed by comparing the starting time with the current time.

1. Add the following components to your main form: a Timer, a Label, two Buttons.

2. In the Object Inspector, set the Enabled property of Timer1 to FALSE, so it won't start automatically after starting the program. Set the Interval of Timer1 to 1000, thus it will "fire" every 1000 milliseconds.
Also set the caption of Label1 to 0, otherwise it would show "Label1" (its name) when the program is started.

3. In the code of the unit, declare a variable "DateTimeStart" of type TDateTime, that remembers the starting time. The variable must be "unit-global", meaning that all the routines of the unit can access it.

4. Add event handlers for the timer and the two buttons. The complete code is quite short, so I copied the entire Implementation section:


{$R *.DFM}

  DateTimeStart: TDateTime; // unit-global variable

procedure TForm1.Button1Click(Sender: TObject);
  Label1.Caption := '0';
  DateTimeStart := Now; // get current date + time
  Timer1.Enabled := True; // start the timer

procedure TForm1.Button2Click(Sender: TObject);
  Timer1.Enabled := False; // stop the timer
  Timer1Timer(Sender); // show elapsed time once more

procedure TForm1.Timer1Timer(Sender: TObject);
  Seconds: integer;
  DateTimeNow: TDateTime;
  DateTimeNow := Now; // get current date + time
  // Calculate time in seconds since Button1 was clicked
  Seconds := Round((DateTimeNow - DateTimeStart)*24*60*60);
  Label1.Caption := IntToStr(Seconds);


It may seem strange that we're not using Timer1 to measure the time elapsed, but only for displaying the time. I.e., it would be simpler if we use an integer variable to keep track of the number of seconds, set to 0 when Button1 is clicked, and incremented by 1 every time that Timer1 fires. But tests have shown that this is not very accurate. Depending on the machine used, this gives a difference of 3 to 5 percent, compared to the solution discussed above.

[ DelphiLand Discussion Forum ]