Posted by Bjorn on May 28, 2007
In Reply to Re: Countdown with timer posted by Stuart Hopkins on
May 16, 2007
: Thanks Bjorn. The code works great. Would you please be able to explain to me how it works?
OK, I've added some comments to my previous message. Hope this helps :)
// declare a variable for counting the remaining seconds // the variable must be accessible by all the routines of the unit, // so declare it before the routines of this unit var Seconds: integer;
At design time, set the Timer's property Interval to 1000 (1000 milliseconds = 1 second) and set property Enabled to false (so that the Timer doesn't start immediately when you start the program).
At run time, start the Timer, e.g. by clicking a button:
Seconds := 1200; // 20 minutes = 1200 seconds Timer1.Enabled := True; // now, start the timer Label1.Caption := '20:00'; // we start counting down from 20 minutes
Source code example for the event handler for the Timer:
var Min, Sec: string; begin if Seconds = 0 then begin // the countdown is over Timer1.Enabled := False; // stop the timer ShowMessage('Done!'); end else begin dec(Seconds); // one second less remaining in the counter // part 1: remaining minutes to show: Min := IntToStr(Seconds div 60); // DIV: integer division (1 min=60secs) // part 2: remaining seconds to show: Sec := IntToStr(Seconds mod 60); // MOD: remainder of integer division // if necessary, add '0' in front of the strings if Length(Min) = 1 then Min := '0' + Min; if Length(Sec) = 1 then Sec := '0' + Sec; // show in format '00:00' Label1.Caption := Min + ':' + Sec; end; end;