🌳
Walking though the Elm woods
  • Introduction
  • Structure of the book
  • Frequently asked questions
    • How can different types share data?
    • How to break Dependency Cycles?
    • How to structure an Elm project?
    • How to turn a Msg into a Cmd Msg?
    • How to update nested Records?
    • What are comparable types?
    • Why are Booleans bad?
    • 🔜Future topics
  • Recipes
    • Writing a Single Page Application
      • Share state across pages
      • Debounced Validation
      • Reusable views
    • Making impossible states Impossible
      • Non empty lists using Zippers
      • Restrict records using Opaque Types
      • Write safer functions using Phantom Types
    • Designing Elm package APIs
      • Create upwards compatible APIs
    • 🔜Future topics
  • Frameworks and packages
    • elm/parser
    • mdgriffith/elm-ui
    • 🔜Future topics
Powered by GitBook
On this page
  • Question
  • Answer
  • Further reading

Was this helpful?

  1. Recipes
  2. Writing a Single Page Application

Debounced Validation

type alias Model =
    { password : String }

type Msg =
    PasswordEntered String

{|- should only start validating if the player has not typed for 500 ms
-}
update : Msg -> Model -> (Model, Cmd Msg)
update msg =
    case msg of
        NameEntered pass =
            { model |> validate pass, Cmd.none }
type alias Model =
    { password : String
    , debouncing : Maybe ( Field, Float )
    }
    
type Msg =
    PasswordEntered String
    | TimePassed
    
update : Msg -> Model -> (Model, Cmd Msg)
update msg =
    case msg of
        NameEntered pass =
            { model | debouncing = Just ( pass, 500 ) }
        TimePassed ->
            case debouncing of
                Just ( pass, secsLeft ) ->
                    if secsLeft <= 0 then
                        ( { model | debouncing = Nothing }
                            |> validate pass
                        , Cmd.none)

                    else
                        ( { model
                            | debouncing =
                                Just
                                    ( pass, secsLeft - checkEveryMs )
                          }
                        , Cmd.none
                        }

            
subscriptions : Model -> Sub Msg
subscriptions { debouncing } =
    case debouncing of
        Just _ ->
            Time.every 100 (always TimePassed)

        Nothing ->
            Sub.none

Question

How can I validate the password only if the user has not typed for 500ms?

Answer

Subscribe to time passing, based on whether a password need to be debounced or not. Start counting down the ms that have passed and then update.

Further reading

PreviousShare state across pagesNextReusable views

Last updated 5 years ago

Was this helpful?

👥Thread:

📦Package:

📦Package:

Example: Debounced Validation
Gizra/elm-debouncer
jinjor/elm-debounce