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.
CodePudding user response:
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)
CodePudding user response:
The first code block of yours, definitely restarts the timer! But it doesn't reset any items, array indexes or variables that your timer procedure might use. Those you have to reset your self in code you write. For example something like:
procedure ReArrangeItemArrayContent;
begin
Timer1.Enabled.False; // Pause the game
Rearrange the array
Reset item index to zero
Timer1.Enabled.True; // Continue the game starting with item[0]
end;
Your second and third block doesn't work because ... the logic is wrong.
But pausing the game is not a good thing. Assuming you have an array that holds the various objects, characters, bombs, rolling stones and what not. Instead of rearranging the array (deleting dead ones or exploded etc. and/or adding new born ones) just mark deleted ones as passive (either by nilling them or setting a boolean field to false), or new ones as active. When you process the items in the timer procedure, you jump over passive ones and move only active ones. Thus, you don't need to pause the game (timer) to shrink or grow the array, you can dynamically manage all items.
You can e.g. start with an array of a few hundreds of items, all nil to begin with. As you create new items you assign them to free slots in the array. If you remove items you assign nil to their slot to indicate it's an empty slot.