How do i create and use a timer?

Under Delphi and free-pascal there is a component called TTimer. Under Smart Mobile Studio however all types of timer objects have a slightly different architecture – and also different names (we will probably provide a TTimer alias before release). The class you are looking for is called “TW3EventRepeater”.

To use a timer start by adding the unit “w3time” to your unit’s uses section. Unlike Delphi, TW3EventRepeater derives from TObject rather than TComponent. There is no point in creating a component (which adds quite a bit of overhead) when a normal object will do.

Using the event repeater from a form is a snap:

unit Form1;

interface

uses w3system, w3ctrls, w3forms, w3application, w3time;

type
TForm1=class(TW3form)
private
 { Private methods }
 FTimer:    TW3EventRepeater;
 FCount:    Integer;
 function   HandleTimer(sender:TObject):Boolean;
protected
  { Protected methods }
  Procedure FormActivated;override;
end;

Implementation

//############################################################################
// TForm1
//############################################################################

Procedure TForm1.FormActivated;
Begin
  FTimer:=TW3EventRepeater.Create(HandleTimer,1000);
end;

function TForm1.HandleTimer(sender:TObject):Boolean;
Begin
  result:=False;
  inc(FCount);
  if FCount>9 then
  Begin
    TW3EventRepeater(sender).free;
    result:=true;
    w3_showmessage('time is up!');
  end;
end;

end.

As expected the timer kicks in after 10 seconds informing us that the time has expired

The timer works just like we expect

The timer works just like we expect

You may have noticed that the callback was a function and not a procedure? If you return “true” the timer will stop of it’s own accord. Since this is javascript and not winapi you can actually dispose of the timer while the timer is called. Because the timer object does not go out of scope until the function returns.

You must be logged in to post a comment.