Archive

Archive for November 13, 2013

Delphi delayed callback function

November 13, 2013 4 comments

When I wrote the Smart Mobile Studio RTL I added a handy function for delayed callback. Under JavaScript this is very easy to achieve and it’s also an important part of an environment that is based on events. In JavaScript everything is about events and all data is received in a non-blocking manner.

But the function is equally handy under Delphi, especially if you want something to execute “after im done with this”. It can be anything from displaying a hint on a form, to start loading data just a few seconds later. Or if you just want to add a form-friendly delay.

NOTE: This code has been replaced by a “non blocking” callback method, click here to view the latest post!

Here is the Delphi implementation of Smart Pascal’s w3_callback function (with a twist).
Note: This function is semi-blocking in the sense that it will halt execution inside the running procedure – but still allow the GUI to be responsive and events to fire. The alternative would be to spawn a thread with a synchronized re-entry.

Procedure w3_Callback(const aCallback:TProc;
          const ms:Integer);
var
  mCount: Integer;
  mThen:  TDateTime;
begin
  if assigned(application)
  and not application.Terminated then
  Begin
    try
      mCount:=0;
      mThen:=dateutils.IncMilliSecond(now,ms);
      repeat
        Sleep(0);
        Inc(mCount);
        if (mCount mod 600)=599 then
        begin
          if Assigned(Application)
          and not (application.Terminated) then
          application.ProcessMessages else
          break;
        end;
      until CompareDateTime(Now,mThen)>=0;
      if Assigned(Application)
      and not (application.Terminated)
      and Assigned(aCallback) then
      aCallback;
    except
      on exception do;
    end;
  end;
end;

How do you use it? With anonymous procedures ofcourse, like this:

  w3_Callback(
    procedure ()
    begin
      showmessage('Your helmet is ready lord vader');
    end,
    1000);