How to make one shot timer function in Delphi (like setTimeout in JavaScript)?

后端 未结 4 1894
广开言路
广开言路 2020-12-25 14:30

The setTimeout is helpful in JavaScript language. How would you create this function in delphi ?

SetTimeOut(procedure (Sender: TObject);
begin
  Self.Counter         


        
4条回答
  •  情话喂你
    2020-12-25 15:29

    Something like

    type
    TMyProc = Procedure of Object(Sender: TObject);
    
    TMyClass = Object
        HandlerList = TStringList;
        TimerList = TStringlist;
    
      Procedure CallThisFunction(Sender :TObject); 
    
      function setTimeout(Timeout: Integer; ProcToCall : TMyProc)
    
    end;
    
    
    
    
    
    
    function setTimeout(Timeout: Integer; ProcToCall : TMyProc)
    var
      Timer : TTimer;
    begin
    
      Timer := TTimer.Create(nil);
      Timer.OnTimer := CallOnTimer;
      Timer.Interval := Timeout;
      Timer.Enabled := true;
      HandlerList.AddObject(ProcToCall);
      TimerList.AddObject(ProcToCall);
    
    end;
    
    
    function CallOnTimer(Sender : TObject)
    var TimerIndex : Integer;
        HandlerToCall : TMyProc;
        Timer : TTimer;
    begin
    
    TimerIndex :=   TimerList.IndexOfObject(Sender);
    HandlerToCall := (HandlerList.Objects[TimerIndex] as TMyProc) ;
    
    HandlerToCall(Self);
    
    HandlerList.Delete(TimerIndex);
    Timer := (TimerList.Objects(TimerIndex) as TTimer);
    Timer.Free;
    TimerList.Delete(TimerIndex);
    
    
    end;
    

    This has just been hacked together and not tested in any way but shows the concept. Basically build a list of the timers and procedures you want to call. As it is the self object is passed to the procedure when it is called but you could build a third list that contained the object to be used as a parameter in the call to setTimeout.

    The Objects are then cleaned up by freeing after the method has been called.

    Not quite the same as javascripts setTimeout but a delphi approximation.

    ps. I haven't really moved on from Delphi7 so if there is a new fangled way of doing this in Delphi XE I don't know about it.

提交回复
热议问题