вторник, 1 декабря 2009 г.

JavaScript like setTimeout function

Delphi standard TTimer component is not handy in some situations - for example, when you need to run something with delay only one or several times, or when you want to use timer in "non-form" unit. New Delphi 2009/2010 anonymous functions feature allows to create JavaScript like setTimeout function.

TProc here is anonymous function type declared in SysUtils unit.

setTimeout returns integer Id of timeout. One may cancel running timeout using cancelTimeout function. Everything is like in JavaScript.

Now you may setup timeout inplace.

My realization of setTimeout function may be downloaded from here.
Note:
The "timeouted" procedure is called in main program thread context.

So code like this:

will not work as wanted and ShowMessage will be called after exit from procedure TForm1.Button1Click(), until you make periodic calls to Application.ProcessMessages from SomethingLongRunning