jinjor / elm-debounce / Debounce

The Debouncer. See the full example here.

Types


type Debounce a

The state of the debouncer.

It is parameterized with the value type a.


type Msg

The messages that are used internally.

Initialize


type alias Config msg =
{ strategy : Strategy
, transform : Msg -> msg 
}

Config contains the debouncing strategy and the message transformation.

This config should be constant and shared between update function and push function.

init : Debounce a

Initialize the debouncer. Call this from your init function.

Strategies


type Strategy

Strategy defines the timing when commands are sent.

soon : Basics.Float -> Strategy

Send command as soon as it gets ready, with given rate limit. (a.k.a. Throttle)

Note: The first command will be sent immidiately.

soonAfter : Basics.Float -> Basics.Float -> Strategy

Similar to soon, but the first command is sent after offset time.

later : Basics.Float -> Strategy

Send command after becomming stable, with given delay time. (a.k.a. Debounce)

manual : Strategy

Send command as soon as it gets ready, but not again until it gets unlocked manually. See unlock.

Typically, unlock is called after previous response comes back.

manualAfter : Basics.Float -> Strategy

Similar to manual, but the first command is sent after offset time.

Sending Commands


type alias Send a msg =
a -> List a -> ( List a
, Platform.Cmd.Cmd msg 
}

This function consumes values and send a command.

If you want to postpone sending, return the values back to keep them.

takeLast : (a -> Platform.Cmd.Cmd msg) -> a -> List a -> ( List a, Platform.Cmd.Cmd msg )

Send a command using the latest value.

takeAll : (a -> List a -> Platform.Cmd.Cmd msg) -> a -> List a -> ( List a, Platform.Cmd.Cmd msg )

Send a command using all the accumulated values.

Update

update : Config msg -> Send a msg -> Msg -> Debounce a -> ( Debounce a, Platform.Cmd.Cmd msg )

This is the component's update function following the Elm Architecture.

e.g. Saving the last value.

( debounce, cmd ) =
    Debounce.update
        { strategy = Debounce.later (1 * second)
        , transform = DebounceMsg
        }
        (Debounce.takeLast save)
        -- save : value -> Cmd Msg
        msg
        model.debounce

The config should be constant and shared with push function.

The sending logic can depend on the current model. If you want to stop sending, return Cmd.none.

push : Config msg -> a -> Debounce a -> ( Debounce a, Platform.Cmd.Cmd msg )

Push a value into the debouncer.

unlock : Config msg -> Platform.Cmd.Cmd msg

Manually unlock. This works for manual or manualAfter Strategy.