The Timer object and how to use it
For time-dependent jobs – a clock, a countdown, animation – the Timer (System tab) is used. It is not visible in the application window, but if it is enabled, it triggers the OnTimer event after the set time, the procedure runs and the application continues its work. The Timer has two properties: Enabled (it works if True and stops if False; True at first) and Interval – the time between events in milliseconds (1000 at first, that is 1 second). 1 second = 1000 milliseconds, so for it to run 20 times a second Interval = 1000 / 20 = 50. For a clock write Label1.Caption := TimeToStr(Now); Now is the current time of the computer clock and TimeToStr converts it to text. A countdown needs a global variable, because the value must be kept from one run of OnTimer to the next; do not give it a property name such as Left, Top, Width or Caption, or inside a form procedure that name will mean the form’s own property. The timer interval is not exact: Windows can delay it slightly, so if exact time is needed, use Now instead of counting ticks.
A quiz app gives 20 seconds for each question. A timer that is not visible on screen fires every second and lowers the number shown by one. When the number reaches zero, the app moves on to the next question.
App and game programmers, makers of sports timing systems and animators control time-based processes with a timer.
Count 10 seconds aloud, “one, two, three…”; if a clock is nearby, compare your count with the real time.
1procedure TForm1.Timer1Timer(Sender: TObject); 2begin 3 Label1.Caption := TimeToStr(Now); 4end;
1procedure TForm1.Timer1Timer(Sender: TObject); 2begin 3 qoldi := qoldi - 1; 4 if qoldi > 0 then 5 Label1.Caption := IntToStr(qoldi) 6 else 7 begin 8 Label1.Caption := 'Start!'; 9 Timer1.Enabled := False; 10 end; 11end;
“The count”: a pair builds a 20-second countdown application, adds a “Stop/Continue” button (Enabled := not Enabled) and calculates in advance how the counting time changes when Interval is changed.