Simple debouncer

I simply add a delayed message step to call my command only if the input is still the same after the delay. It also allows me to easily add some validation (not included in the example below for readability).

delayMsg : msg -> Cmd msg
delayMsg msg =
    Task.perform (always msg) (Process.sleep 1000)


-- in your update cases:

GotFieldInput fieldInput ->
    ( { model | fieldInput = fieldInput }
    , delayMsg (GotDelayedFieldInput fieldInput)
    )

GotDelayedFieldInput fieldInput ->
    if fieldInput == model.fieldInput then
        ( { model | status = Loading }, costlyCommand fieldInput )
    else
        ( model, Cmd.none )

I don’t see how it could be simpler :wink:

5 Likes