Reputation: 397
How can I pause TTimer
in Delphi with keeping interval? So, for instance, I have TTimer
that has 10 seconds interval and when I set timer to pause after first 7 seconds of working, it will save its state, and then when I resume timer it will fire after remaining 3 seconds.
Thanks a lot guys!
Upvotes: 6
Views: 7373
Reputation: 613491
You cannot do that with a TTimer
which is a loose wrapper around the SetTimer
API.
In order to do this you would need to keep track of when the timer started and when you paused it. Then you would know how much time was left. When you need to pause, set the timer Enabled
property to False
and set the interval to be the amount of time remaining. Don't forget that after the timer fires for the first time you need to reset its interval to the true interval.
As you can see from the above, a TTimer
is not the best fit for your problem. But, having said that it would not be terribly difficult, and quite fun, to produce a TTimer
variant that supported pausing the way you desire.
Upvotes: 9
Reputation: 598134
TTimer
does not support what you are asking for. As others have already commented, you would have to stop the timer, reset its Interval
to whatever time is remaining, start it, then stop and reset its Interval
back to 10 seconds when the next OnTimer
event is triggered.
A simpler solution is to just let the TTimer
keep running normally, and have a separate flag that tells the OnTimer
event handler whether it can do its work or not whenever it is triggered, eg:
var
Boolean: Paused = False;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if not Paused then
begin
// do proccess
end;
end;
procedure TForm1.PauseButtonClick(Sender: TObject);
begin
Paused := True;
end;
procedure TForm1.ResumeButtonClick(Sender: TObject);
begin
Paused := False;
end;
Upvotes: 1
Reputation: 665
Timer.interval :=1000;
ICount:integer;
In create procedure set icount to 0
Procedure timerevent(sender:tobject);
Begin
If icount=10 then
Begin
// do proccess
Icount = 0;
End;
Inc(icount);
End;
Now you can stop the timer anywhere
Upvotes: 13
Reputation: 163357
That's not how the Windows timer facility works, and that's not how the Delphi wrapper works, either.
When you disable the timer, keep note of how much time was remaining before it was due to fire again. Before you re-enable it, set the Interval
property to that value. The next time the timer fires, reset Interval
to the original value.
Upvotes: 2