'How to restart a timer's ontimer event Delphi

Everywhere on the internet people say the way to restart a timer is by doing the following, however this only seems to "pause" the timer and once its re-enabled it carries on from where it stops:

timer1.enabled:=False;
timer1.enabled:=True;

The following should never display the message if the timer restarts, and yet it does:

procedure TForm1.restarttimer;
begin
  Timer1.Enabled := False;
  Timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
  restarttimer;
  showmessage('Hello');
end;

Is there a way to restart the timer in a way that the Ontimer event itself restarts from its first line? ie. The showmessage in the code above would never display.



Solution 1:[1]

I suppose you want to reset the timer so that if say it was counting 1 min and something else happened during that which needs to make it count another 1 min, you don't want it to count just the rest of the time that was remaining

according to https://www.delphigroups.info/2/6d/169892.html

The TTimer restarts when you

  • change Enabled from false to true
  • set a different non zero Interval
  • set a non nil OnTimer event, even with the same value as before.

I see you tried the first and you say it doesn't work, but seems you're thinking wrongly that the timer is a countdown like say in Javascript, whereas it is an interval counter that you don't need to restart in the event handler (like you'd do in a countdown one to make it behave like an interval-repeating counter)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George Birbilis