Debounced Validation
Problem
Solution
1
type alias Model =
2
{ password : String }
3
​
4
type Msg =
5
PasswordEntered String
6
​
7
{|- should only start validating if the player has not typed for 500 ms
8
-}
9
update : Msg -> Model -> (Model, Cmd Msg)
10
update msg =
11
case msg of
12
NameEntered pass =
13
{ model |> validate pass, Cmd.none }
Copied!
1
type alias Model =
2
{ password : String
3
, debouncing : Maybe ( Field, Float )
4
}
5
6
type Msg =
7
PasswordEntered String
8
| TimePassed
9
10
update : Msg -> Model -> (Model, Cmd Msg)
11
update msg =
12
case msg of
13
NameEntered pass =
14
{ model | debouncing = Just ( pass, 500 ) }
15
TimePassed ->
16
case debouncing of
17
Just ( pass, secsLeft ) ->
18
if secsLeft <= 0 then
19
( { model | debouncing = Nothing }
20
|> validate pass
21
, Cmd.none)
22
​
23
else
24
( { model
25
| debouncing =
26
Just
27
( pass, secsLeft - checkEveryMs )
28
}
29
, Cmd.none
30
}
31
​
32
33
subscriptions : Model -> Sub Msg
34
subscriptions { debouncing } =
35
case debouncing of
36
Just _ ->
37
Time.every 100 (always TimePassed)
38
​
39
Nothing ->
40
Sub.none
Copied!

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