Search code examples
delphisleeptms-web-core

How do I use the `Sleep()` procedure in TMS WEB Core?


Normally in VCL and FMX, you can use Sleep() to pause execution of code. So something like this as an example:

while true do
begin
  // Do some code
  Sleep(50);
end;

So after every iteration, it will wait 50 milliseconds.

I'm able to write the above code in TMS WEB Core and it compiles without any issues. There are no design-time or run-time errors.

But in run-time, it doesn't seem to work. It doesn't wait 50 milliseconds. I've set it to Sleep(50000) even and it's still instant. It doesn't pause execution of the code. Seems like Sleep is just ignored.

How does Sleep() work in TMS WEB Core?


Solution

  • Looks like Sleep() isn't available in TMS WEB Core even though it compiles and runs without any errors.

    There is however an AsyncSleep function from the Rtl.HTMLUtils unit that you can use. It's used within an Await() method like this:

    Await(boolean, AsyncSleep(50));
    

    It's not Sleep(), but it's the best alternative I could find and it seems to work the same as Sleep().

    You do however need to mark the procedure or function as an [async] method in the declaration.

    Here's an example:

      TForm1 = class(TWebForm)
        WebButton1: TWebButton;
    
        [async]
        procedure WebButton1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    uses
      Rtl.HTMLUtils;
    
    procedure TForm1.WebButton1Click(Sender: TObject);
    begin
      console.log('A');
    
      Await(boolean, AsyncSleep(2000));
    
      console.log('B');
    end;
    

    With the above code, you'll see that B gets logged two seconds after A.

    Also, if you don't mark it as [async], you'll get await only available in async procedure error.