gschier
5/20/2016 - 2:36 AM

debounce.elm

import Html exposing (..)
import Html.Attributes exposing (placeholder)
import Html.App as App
import Html.Events exposing (onInput)
import Process
import Task

main : Program Never
main =
    App.program
        { init = init
        , update = update
        , subscriptions = \_ -> Sub.none
        , view = view
        }


init : (Model, Cmd Msg)
init = (initialModel, Cmd.none)


-- Model


type alias Model =
    { value : String
    , pending : String
    }


initialModel : Model
initialModel =
    { value = ""
    , pending = ""
    }


-- Update


type Msg
    = NoOp
    | NewInput String
    | SetInput String


update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case (Debug.log "update" msg) of
        NewInput value ->
            let
                task = Process.sleep 400
                error = \_ -> NoOp
                success = always (SetInput value)
            in
                ({ model | pending = value }, Task.perform error success task)

        SetInput value ->
            if model.pending == value then
                ({ model | value = value }, Cmd.none)
            else
                (model, Cmd.none)

        NoOp ->
            (model, Cmd.none)


-- View


view : Model -> Html.Html Msg
view model =
    div [ ]
        [ h1 [ ] [ text ("Debounced: " ++ model.value) ]
        , input [ onInput NewInput, placeholder "Debounce Me" ] [ ]
        ]