Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timers In Delphi

Tags:

delphi

Consider the following code

Timer1 .Enabled := False;
Timer1.Interval : = 300;
For I := 1 to NumberOfTimesNeed do
Begin

   Timer1 .Enabled := False;    //  
   Timer1 .Enabled := True;     // reset the timer to 0.30 seconds

   TakesToLong     := False;
   DoSomethingThatTakesTime;    // Application.ProcessMessages is called in the procedure

   If TakesToLong = True then 
      TakeAction;
End;

procedure Timer1Timer(Sender: TObject);
begin
   TakesToLong:= True;
end;

Question :

When I disable and then enable the Timer1 with

Timer1.Enabled := False;
Timer1.Enabled := True;

Does this reset the timer ?

i.e. will it always wait 0.30 Seconds before timing out.

like image 232
Charles Faiga Avatar asked Nov 28 '22 21:11

Charles Faiga


1 Answers

Yes, it will. Setting Enabled to False will call the Windows API function KillTimer() if the timer was enabled before. Setting Enabled to True will call the Windows API function SetTimer() if the timer was not enabled before.

It's a standard idiom, which has been working since the times of Delphi 1.

I would however implement your code in a different way:

Start := GetSystemTicks;
DoSomethingThatTakesTime;
Duration := GetSystemTicks - Start;

if Duration > 300 then
  TakeAction;

which would work without a timer, and without the need to call ProcessMessages() in the long-taking method. GetSystemTicks() is a function I have in a library, which does call timeGetTime() in Windows, and which was implemented differently for Kylix (don't remember how, I purged that code long ago).

like image 108
mghie Avatar answered Dec 20 '22 04:12

mghie