File: Debounce.hs

package info (click to toggle)
haskell-auto-update 0.1.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 112 kB
  • sloc: haskell: 373; makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,715 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{-# LANGUAGE ScopedTypeVariables #-}
-- | Debounce an action, ensuring it doesn't occur more than once for a given
-- period of time.
--
-- This is useful as an optimization, for example to ensure that logs are only
-- flushed to disk at most once per second.
--
-- Example usage:
--
-- @
-- printString <- 'mkDebounce' 'defaultDebounceSettings'
--                  { 'debounceAction' = putStrLn "Running action"
--                  , 'debounceFreq' = 5000000 -- 5 seconds
--                  , 'debounceEdge' = 'DI.trailingEdge' -- Trigger on the trailing edge
--                  }
-- @
--
-- >>> printString
-- Running action
-- >>> printString
-- <Wait five seconds>
-- Running action
--
-- See the fast-logger package ("System.Log.FastLogger") for real-world usage.
--
-- @since 0.1.2
module Control.Debounce
    ( -- * Type
      DI.DebounceSettings
    , defaultDebounceSettings
      -- * Accessors
    , DI.debounceFreq
    , DI.debounceAction
    , DI.debounceEdge
    , DI.leadingEdge
    , DI.trailingEdge
      -- * Creation
    , mkDebounce
    ) where

import           Control.Concurrent      (newEmptyMVar, threadDelay)
import qualified Control.Debounce.Internal as DI

-- | Default value for creating a 'DebounceSettings'.
--
-- @since 0.1.2
defaultDebounceSettings :: DI.DebounceSettings
defaultDebounceSettings = DI.DebounceSettings
    { DI.debounceFreq = 1000000
    , DI.debounceAction = return ()
    , DI.debounceEdge = DI.leadingEdge
    }

-- | Generate an action which will trigger the debounced action to be performed.
--
-- @since 0.1.2
mkDebounce :: DI.DebounceSettings -> IO (IO ())
mkDebounce settings = do
  baton <- newEmptyMVar
  DI.mkDebounceInternal baton threadDelay settings