Recent

Author Topic: is there a timeout function in FPC that I can use to terminate a While/Do loop?  (Read 420 times)

billd

  • Jr. Member
  • **
  • Posts: 51
All,

Is there any kind of time out function that I can use as one of the parameters to terminate a While/Do loop?

I have the below code example (not perfect syntax for this post) that reads input from a bar code scanner. Most scanners are like a keyboard in that they terminate the scan with a <CR>, but not all scanners.  I would like to terminate the loop below based on either the criteria that the <CR> was found or x milliseconds have passed.

I did a search and there seem to be some timer functions, but I could  not find any code examples and I am unsure how to implement them.

Program ReadScanner

instring:='';
InitKeyBoard;
  Writeln;
  Writeln('----------------Scan now or push ESC for main menu.--------------------');

  while H<>CR do   OR TIMEOUT  //terminate with a CR or a TimeOut. Is there anything I can use for TIMEOUT?
    begin
      K:=GetKeyEvent;
      K:=TranslateKeyEvent(K);
      if K<>ESC_CODE then
        Begin
         H:=GetKeyEventChar(k);
         abc:=GetKeyEventCode(k);
         ch:=KeyEventToString(K);
         if (GetKeyEventChar(K)<>CR) then instring:=instring+chr(abc); 
     end;

   DoneKeyBoard;       

Fibonacci

  • Full Member
  • ***
  • Posts: 219
  • #PDK
Timeout 5s

Code: Pascal  [Select][+][-]
  1. var
  2.   q: qword;
  3.  
  4. begin
  5.   q := GetTickCount64;
  6.  
  7.   while true do begin
  8.     if GetTickCount64 > q+5000 then break;
  9.  
  10.     //do your stuff...
  11.     sleep(10);
  12.   end;

billd

  • Jr. Member
  • **
  • Posts: 51
Thanks!  I will try to work that into a TimeOut function.

I guess I could pass an initial value to the TimeOut function and have it return True after x number of ticks.

- Bill

mas steindorff

  • Hero Member
  • *****
  • Posts: 526
one thing you should note is that your while loop is a bad design now days.  your code is only one of several functions that run from the real main "application".  by never returning, you risk the chance other services will be starved and that the mouse, keyboard, and timer events will no be processed.
two ways for a better solution: 
1: add application.processmessages within your loop or
2: best: use a timer and add your code from inside your loop. the timer's interval becomes your outer loop.
Mas
windows 7/10 - laz 2.0 / 1.2.6 general releases

Fibonacci

  • Full Member
  • ***
  • Posts: 219
  • #PDK
But what if its a console app or the loop is in another thread? You made assumptions without enough data

KodeZwerg

  • Hero Member
  • *****
  • Posts: 1719
  • Fifty shades of code.
    • Delphi & FreePascal
Depending how accurate the timing must be, I'd suggest do use TTimer, TEpicTimer or TStopWatch and increase a Form field value that you check inside your loop if it shall break.
« Last Edit: Tomorrow at 31:76:97 by KodeZwerg »

 

TinyPortal © 2005-2018