How to get timeleft in Timer? [duplicate]

2019-04-14 01:04发布

问题:

Possible Duplicate:
Delphi Timer: Time before next event

How to get current timeleft when timer will be executed ?

for example:

I create a timer with interval 60 000

procedure TForm1.my_Timer(Sender: TObject);
begin
  // do something
end;

Then I create another timer (interval 1000) which reason is to get the timeleft of the first timer

procedure TForm1.second_Timer(Sender: TObject);
begin
  second_Timer.Interval := 1000;
  Label1.Caption := IntToStr(my_Timer.timeleft); // How ???
end;

Thanks.

回答1:

You can't get this information from the timer. The best you can do is make a note of when the timer last fired and work it out for yourself. For example you can use TStopwatch to do this.



回答2:

TTimer itself does not have have this capability. One option would be to use the tag property of the first timer to store the remaining time like so:

procedure TForm1.MyTimerTimer(Sender: TObject);
begin
  MyTimer.Tag := MyTimer.Interval;
  // Do something
end;

procedure TForm1.Second_TimerTimer(Sender: TObject);
begin
  MyTimer.Tag := MyTimer.Tag - Second_Timer.Interval;
  Label1.Caption := 'Time Left '+IntToStr(MyTimer.Tag);
end;


回答3:

Just created my hack way, I'm using two global vars

var
  my_timer_interval_hack : integer;
  my_timer_timeleft_hack : integer;

procedure TForm1.my_Timer(Sender: TObject);
begin
  // do something


  // hack, reset timer TimeLeft
  my_timer_timeleft_hack := my_Timer.Interval;
end;



procedure TForm1.second_Timer(Sender: TObject);
begin
  second_Timer.Interval := 1000;

  // hack get timeleft from my_timer
  my_timer_timeleft_hack := my_timer_timeleft_hack - 1000;
  if my_timer_timeleft_hack <= 0 then
    my_timer_timeleft_hack := my_timer.Interval;

  Label1.Caption := IntToStr(my_timer_timeleft_hack);
end;


标签: delphi timer