Looking for a "wait until x or timeout" design pattern..

Ken Corey ken at kencorey.com
Sun Jan 29 14:38:06 EST 2012


Here's the basic idea of the code I needed.

the touchMove event arrives in no particular order, and in no particular 
time.

If you absolutely have to have a timeout, you can't just test for a 
timestamp on the next run of touchMove, because there might not be 
another touchMove.

I'm not quite clear on what the "wait 50 milliseconds with messages" 
command does.  Is that a more succinct way of putting it?

-Ken


-------------------8<-------------------------------
-- Semaphore handling for touch movements
-- 
-- This code is meant to be used to group random events that
-- happen in a timeframe, group them together, and take action
-- on those events as a whole.
--
-- User input is pseudo-random, and we therefore cannot count on
-- events coming in a particular order, or even coming at all.
--
-- I use code similar to this to group several distinct user inputs and
-- deal with several at a time.  If no more events come within the
-- delay period, we fire the handler.
--
-- This isn't perfect, as there doesn't seem to be a way to cancel a
-- pending send...so we guard against the send happening in
-- performAction.
--
-- What this means is that the delay (50 milliseconds below) must
-- be chosen carefully so that there's only one group of data waiting
-- to be processed.
--
-- If the touchMove event happens but is delayed, and another
-- touchMove event with immediate execution happens within the
-- timeout period, the second touchMove event clears the sSemaphore,
-- so then the delayed performAction from the first touchMove event
-- is ignored.
--

local sDetails,sSemaphore

on touchMove pID,pX,pY
    -- check to see if we've dealt with pID before
    if pID is in the keys of sSemaphore then
       -- have seen it before so take action immediately
       put (pX&comma&pY) into sSemaphore[pID]
       send "performAction "&pID&","&pX&","&pY
    else
       -- haven't seen it, only do it after a delay
       put (pX&comma&pY) into sSemaphore[pID]
       send "performAction "&pID&","&pX&","&pY to me in 50 milliseconds
    end if
end touchMove

on performAction
    -- check to see if it's already been handled.
    if the number of lines in the keys of sSemaphore > 0 then
       -- nope, let's get busy

       -- code to deal with the data

       delete variable sSemaphore
    end if
end performAction





More information about the use-livecode mailing list