Skip to content

Instantly share code, notes, and snippets.

@natefaubion
Last active November 30, 2017 04:11
Show Gist options
  • Save natefaubion/3405f930b9008e52e5d995681a7d6f2b to your computer and use it in GitHub Desktop.
Save natefaubion/3405f930b9008e52e5d995681a7d6f2b to your computer and use it in GitHub Desktop.
type Debouncer =
{ var :: AVar Unit
, timer :: Fiber Unit
}
type State =
{ debouncer :: Maybe Debouncer
}
debounceTimeout :: Milliseconds -> AVar Unit -> Aff (avar :: AVAR | eff) (Fiber Unit)
debounceTimeout ms var = forkAff do
delay ms
putVar unit var
eval (SomeInput next) = do
st <- H.get
case st.debouncer of
-- No debouncing yet
Nothing -> do
var <- H.liftAff makeEmptyVar
timer <- H.liftAff (debounceTimeout (Milliseconds 500.0) var)
_ <- H.fork do
-- Wait for the var to resolve
H.liftAff (takeVar var)
-- Reset state and run debounced effect
H.modify _ { debouncer = Nothing }
runMyCode
let
debouncer = { var, timer }
H.modify _ { debouncer = Just debouncer }
-- We are already debouncing
Just { var, timer } -> do
-- Kill the old timer and allocate a new one
H.liftAff $ killFiber timer
nextTimer <- H.liftAff (debounceTimeout (Milliseconds 500.0) var)
let
debouncer = { var, timer: nextTimer }
H.modify _ { debouncer = Just debouncer }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment